Code Snippets
/

PHP Array Functions Cheat Sheet

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.

PHP
Easy
3 snippets
php-array-functions
map-filter-reduce
functional-programming

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 ...; }.