devnotes.

Essential Array Functions

PHP has one of the richest built-in array function libraries of any language — over 80 functions. Some of the most commonly used:

Transforming:

array_map(fn ($x) => $x * 2, $arr);       // apply a function to every element
array_filter($arr, fn ($x) => $x > 10);    // keep elements matching a condition
array_reduce($arr, fn ($c, $x) => $c + $x, 0); // fold to a single value

Sorting:

sort($arr);       // sort values ascending, reindexes keys
rsort($arr);       // descending
asort($arr);        // sort by value, preserve keys (good for assoc arrays)
ksort($arr);         // sort by key
usort($arr, fn ($a, $b) => $a['price'] <=> $b['price']); // custom comparator

Searching & checking:

in_array('red', $colors);      // true/false
array_search('red', $colors);  // returns the key, or false
array_key_exists('name', $arr);

Combining & slicing:

array_merge($a, $b);        // combine arrays
array_slice($arr, 0, 3);     // first 3 elements
array_unique($arr);           // remove duplicate values
array_keys($arr); array_values($arr);
implode(', ', $arr);          // array to string
explode(',', $string);        // string to array

Most of these functions do not mutate the original array — they return a new one — which fits well with predictable, functional-style code.

PHP Array Functions: map, filter, sort & more | DevNotes