Array functions and sorting

PHP · Practical · 14 min

Idiomatic PHP leans on the built-in array functions instead of hand-written loops for common transformations.

PHP ships with dozens of array functions. The core trio:

  • array_map($fn, $array) transforms every value. With one array it keeps the keys.
  • array_filter($array, $fn) keeps values for which $fn returns true. Without a callback it drops falsy values. It preserves keys, so wrap it in array_values() when you need a clean list.
  • array_reduce($array, $fn, $initial) folds the array into one value.

Note the inconsistent argument order (callback first for array_map, second for array_filter), a famous PHP quirk. Named arguments help when in doubt.

PHP 8.4 added array_find, array_find_key, array_any and array_all, which replace many manual search loops.

Other workhorses: array_column($rows, 'email', 'id') extracts a column from rows (optionally keyed), array_combine, array_flip, array_unique, array_slice, array_merge (renumbers int keys) versus + (keeps the left side's keys), and range(1, 10).

Sorting functions sort in place and return true:

  • sort/rsort sort values and reindex.
  • asort/arsort sort by value keeping keys; ksort/krsort sort by key.
  • usort($a, fn($x, $y) => $x['age'] <=> $y['age']) sorts with a comparator. The spaceship operator <=> returns -1, 0 or 1, and arrays compare element by element, so [$a->last, $a->first] <=> [$b->last, $b->first] sorts by two fields.

PHP's sort is stable since 8.0.

Example

<?php
$people = [
    ['id' => 3, 'name' => 'Cy', 'age' => 41],
    ['id' => 1, 'name' => 'Ana', 'age' => 29],
    ['id' => 2, 'name' => 'Ben', 'age' => 35],
];

$names = array_map(fn($p) => $p['name'], $people);
echo implode(',', $names), "\n";             // Cy,Ana,Ben

$over30 = array_filter($people, fn($p) => $p['age'] > 30);
print_r(array_keys($over30));                // [0, 2]: keys kept

$total = array_reduce($people, fn($sum, $p) => $sum + $p['age'], 0);
echo $total, "\n";                           // 105

usort($people, fn($a, $b) => $a['age'] <=> $b['age']);
echo $people[0]['name'], "\n";               // Ana

print_r(array_column($people, 'name', 'id')); // [1 => Ana, 2 => Ben, 3 => Cy]

Remember

  • array_map, array_filter and array_reduce cover most loops
  • array_filter keeps keys; reindex with array_values
  • Sort functions work in place; usort plus <=> handles custom orders

Watch out for

  • Writing $sorted = sort($items); sort returns true and modifies $items in place.

Check yourself

  1. What does array_filter([5, 0, 7]) return?
  2. Which call sorts an associative array by value but keeps key => value pairs?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.php.net/manual/en/ref.array.php