PHP Snippet

PHP Array Functions Cheat Sheet

Difficulty: Easy

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.

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

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