PHP Array Functions

How to change array key case to upper or lower?

To change array keys to upper or lower case following function is used:

<?php

// declare cars array
$carsList = [
    'mazda'  => 'GS/GT',
    'toyota' => 'Corolla'
];

// change array keys to uppercase
$carsList = array_change_key_case($carsList, CASE_UPPER);

// show results
print_r($carsList);

// change array keys to lowercase
$carsList = array_change_key_case($carsList);

// show results
print_r($carsList);

How to fetch specific keys as array from multi-dimensional array?

If you have a multi-dimensional array and you want to retrieve particular keys as an array you can easily do this using following array function.

<?php

// assume database returns
// arrays of records as below
$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);

// get all the first names
$first_names = array_column($records, 'first_name');

// get all the last names but keep id as array keys
$last_names = array_column($records, 'last_name', 'id');

// debug array
var_dump($first_names, $last_names);

How to merge arrays in php?

To mege array in php array_merge function is used. Followings are some of the hight lights of this function

  • It merges two arrays into one
  • If both array has common keys values from the second array will be considered
  • New array elements will be appeneded.
  • Numeric keys will be renumbered.
<?php

// prepare keys and value array
$valArray = ['color' => 'red', 'vehicle' => 'car', 'circle'];
$keyArray = ['color' => 'blue', 'vehicle' => 'truck', 'shape' => 'rectangle'];

// combine keys and values
$combinedArr = array_merge($keyArray, $valArray);
print_r($combinedArr);


// If you want to append array elements from the second array to the first array
// while not overwriting the elements from the first array and not re-indexing
// The keys from the first array will be preserved
// If an array key exists in both arrays, then the element from the first array will be used
$array1 = ['one', 'two', 'three'];
$array2 = ['four', 'five', 'six', 'seven'];

$result = $array1 + $array2;
print_r($result);


// observe the difference
// prepare keys and value array
$keyArray = ['color', 'vehicle', 'shape'];
$valArray = ['blue', 'truck', 'rectangle'];

$combined = array_combine($keyArray, $valArray);
print_r($combined);

How to get list of array keys and values?

Followings are some of the useful function that deals with array keys and values:

<?php

// declare colors array
$colors  = ['blue', 'red', 'blue', 'green', 'yellow', 'blue'];

// get all keys for colors array
$keys = array_keys($colors);
$blueKeys = array_keys($colors, "blue");

// get all values for colors array
$values = array_values($colors);

// debug
print_r($keys);
print_r($values);
print_r($blueKeys);

// get first key of colors array
$firstKey = array_key_first($colors);

// get last key of colors array
$lastKey = array_key_last($colors);

How to count repeated values in array?

<?php

// declare colors array
$colors  = ['blue', 'red', 'blue', 'green', 'yellow', 'blue'];

// find number of times value appeared in an array
$result = array_count_values($colors);

// count total elements in array
$total = count($colors);

// debug
print_r($total);
print_r($result);

How to sort arrays in php?

Followings are some of the functions that can help you with array sorting:

<?php

// How to sort array values?
$colors  = ['blue', 'red', 'blue', 'aqua', 'green', 'yellow', 'blue'];

// duplicate array
$colors2 = $colors;
$colors3 = $colors;
$colors4 = $colors;

// sort an array by value
// does not maintain indexes/keys
sort($colors);
print_r($colors);

// sort an array by value
// maintain indexes/keys
asort($colors2);
print_r($colors2);


// sort an array in reverse
// order from high to low
rsort($colors);
print_r($colors);

// sort an array by values using
// a user-defined comparison function
// does not maintain indexes/keys
usort($colors3, function ($a, $b) {
    return $a <=> $b;
});

print_r($colors3);

// sort an array by values using
// a user-defined comparison function
// maintain indexes/keys
uasort($colors4, function ($a, $b) {
    return $a <=> $b;
});

print_r($colors4);


// define multi-dimensional array
$multiArr = [
  ['a' => 1, 'b' => 2, 'c' => 2],
  ['a' => 4, 'b' => 5, 'c' => 4],
  ['a' => 7, 'b' => 8, 'c' => 3],
];

$keyToSort = 'c';
usort($multiArr, function ($a, $b) use ($keyToSort) {
    return $a[$keyToSort] <=> $b[$keyToSort];
});

print_r($multiArr);


// How to sort array keys?
$colors  = ['blue' => 1, 'red' => 2, 'aqua' => 4, 'green' => 5, 'yellow' => 6];

// sort an array by keys using
// a user-defined comparison function
uksort($colors, function ($a, $b) {
    return $a <=> $b;
});

print_r($colors);

Sorting functions in php

Function Sort By Maintains Key Order By
array_multisort() value associative yes, numeric no first array or sort options
asort() value yes low to high
arsort() value yes high to low
krsort() key yes high to low
natcasesort() value yes natural, case insensitive
natsort() value yes natural
rsort() value no high to low
sort() value no low to high
uasort() value no user defined
uksort() key yes user defined
usort() value yes user defined
ksort() key yes low to high