Array

PHP Array Function

array_change_key_case()

array_change_key_case(array $array, int $case = CASE_LOWER): array

Change key cases

Case options

  • CASE_UPPER
  • CASE_LOWER
function arrayKeyToLowercase(array $array): array
{
  return array_change_key_case($array, CASE_LOWER);
}

function arrayKeyToUppercase(array $array): array
{
  return array_change_key_case($array, CASE_UPPER);
}


$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));

Array
(
    [FIRST] => 1
    [SECOND] => 4
)

array_reverse()

array_reverse(array $array, bool $preserve_keys = false): array

Return an array with elements in reverse order

$input  = [
  "php", 
  4.0, 
  [
    "green",
    "red"
  ]
];
$reversed = array_reverse($input);


print_r($input);
// Array
// (
//     [0] => php
//     [1] => 4
//     [2] => Array
//         (
//             [0] => green
//             [1] => red
//         )
// )

print_r($reversed);

// Array
// (
//     [0] => Array
//         (
//             [0] => green
//             [1] => red
//         )
//     [1] => 4
//     [2] => php
// )

array_map()

array_map(?callable $callback, array $array, array ...$arrays): array

Applies the callback to the elements of the given arrays

function cube($n)
{
    return ($n * $n * $n);
}

$a = [1, 2, 3, 4, 5];
$b = array_map('cube', $a);
print_r($b);

// Array
// (
//     [0] => 1
//     [1] => 8
//     [2] => 27
//     [3] => 64
//     [4] => 125
// )

Explode string and trim value into a new array

function arrayExplodeTrim(
  string $separator,
  string $string,
  int $limit = PHP_INT_MAX
): array {
  $explode_array = explode($separator, $string, $limit);
  return array_map('trim', $explode_array);
}