PHP Array Functions Cheat Sheet
PHP's array library is dense; once you know `array_map`, `array_filter`, `array_reduce`, and a few of their cousins, most array work becomes one-liners. This snippet covers the trio plus the surprising key-preserving behaviour of `array_filter` and the keys-to-values pivot via `array_combine`. Reach for these instead of writing manual `foreach` loops.
516 views
6
<?php
$nums = [1, 2, 3, 4, 5, 6];
$squares = array_map(fn($n) => $n * $n, $nums);
print_r($squares); // [1, 4, 9, 16, 25, 36]
$evens = array_filter($nums, fn($n) => $n % 2 === 0);
print_r($evens);
// CAREFUL: array_filter preserves the original keys.
// Array ( [1] => 2 [3] => 4 [5] => 6 )
// Use array_values() to renumber:
print_r(array_values($evens));array_map returns a new array of the callback's return values; the input array's keys are preserved when called on a SINGLE array. array_filter keeps elements where the callback is truthy. The classic gotcha is that array_filter keeps the ORIGINAL keys even though the values are now sparse: when JSON-encoding the result, PHP will emit an object literal because keys are no longer 0..n-1. Wrap the result in array_values(...) whenever you want a clean numerically-indexed list. Arrow functions (fn($x) => $x * 2) require PHP 7.4+; pre-7.4 you used function ($x) use ($outer) { return ...; }.
$nums = [1, 2, 3, 4, 5];
$sum = array_reduce($nums, fn($acc, $n) => $acc + $n, 0);
echo "sum=$sum\n";
$product = array_reduce($nums, fn($acc, $n) => $acc * $n, 1);
echo "product=$product\n";
// Build a hash from a list of pairs.
$pairs = [["ada", 36], ["linus", 54], ["margaret", 88]];
$ages = array_reduce($pairs, function ($acc, $pair) {
$acc[$pair[0]] = $pair[1];
return $acc;
}, []);
print_r($ages);array_reduce($arr, $callback, $initial) walks the array left-to-right with an accumulator, returning the final accumulator. The seed is mandatory if you want a known starting value; pass null to mean 'no seed' but be ready for a null first iteration. The pattern of building an associative array from a list of pairs comes up constantly when normalising parsed CSV or query results; array_combine($keys, $values) is shorter when you already have parallel arrays. For numeric sums, array_sum($nums) is even shorter and avoids the callback overhead.
$keys = ["red", "green", "blue"];
$values = ["#f00", "#0f0", "#00f"];
$colors = array_combine($keys, $values);
print_r($colors);
// Array ( [red] => #f00 [green] => #0f0 [blue] => #00f )
// array_keys / array_values flip the perspective.
$keysOnly = array_keys($colors);
print_r($keysOnly);
// array_flip swaps keys and values (collapsing duplicates).
$reverse = array_flip($colors);
print_r($reverse);
// in_array vs array_key_exists: the first checks values, the second keys.
var_export(in_array("#f00", $colors));
echo "\n";
var_export(array_key_exists("red", $colors));
echo "\n";array_combine zips two parallel arrays into an associative array using the first as keys; both must be the same length. array_keys and array_values give you a clean numerically-indexed list of either side, useful for re-indexing after a filter. array_flip swaps keys and values, collapsing duplicates silently, which is the fastest way to dedupe a list (then call array_keys on the result). Distinguish in_array($v, $arr) (linear scan over values) from array_key_exists($k, $arr) and isset($arr[$k]): isset returns false on a key whose value is null, while array_key_exists returns true; pick based on whether null is a meaningful state in your data.
