Array functions
Many array tasks repeat: transform every element, pick the matching ones, compute a total. PHP has ready-made functions for them — code that uses them is shorter than a loop and shows at once what it does.
array_map
array_map() applies a function to every element and returns a new array:
<?php
$prices = [100, 250, 400];
$withTax = array_map(fn ($price) => $price * 1.2, $prices);
echo implode(', ', $withTax); // 120, 300, 480The function comes first, the array second.
array_filter
array_filter() keeps the elements for which the function returned true:
<?php
$numbers = [5, 12, 8, 20];
$big = array_filter($numbers, fn ($number) => $number > 10);
echo implode(', ', $big); // 12, 20Here the argument order is reversed: the array first, then the function.
array_reduce
array_reduce() reduces an array to a single value. The function receives the accumulated result and the next element:
<?php
$cart = [100, 250, 400];
$total = array_reduce($cart, fn ($sum, $price) => $sum + $price, 0);
echo $total; // 750The third argument is the initial value. For a plain sum there is the ready-made array_sum().
A chain of transformations
Functions can be combined: the result of one goes into another:
<?php
$orders = [
['total' => 500, 'paid' => true],
['total' => 300, 'paid' => false],
['total' => 200, 'paid' => true],
];
$paid = array_filter($orders, fn ($order) => $order['paid']);
$totals = array_column($paid, 'total');
echo array_sum($totals); // 700array_column() pulls the values of one key out of an array of arrays.
Searching
<?php
$fruits = ['apple', 'pear', 'plum'];
var_dump(in_array('pear', $fruits)); // bool(true)
echo array_search('plum', $fruits); // 2in_array() tells whether a value is present, and array_search() returns its key or false.
Parts of an array
<?php
$numbers = [1, 2, 3, 4, 5];
echo implode(', ', array_slice($numbers, 1, 3)), "\n"; // 2, 3, 4
echo implode(', ', array_merge([1, 2], [3, 4])), "\n"; // 1, 2, 3, 4
echo implode(', ', array_unique([1, 2, 2, 3, 1])), "\n"; // 1, 2, 3
echo implode(', ', array_reverse($numbers)); // 5, 4, 3, 2, 1All these functions return a new array and leave the original untouched.
Common mistake
array_filter() keeps the original keys, so the result has "gaps" in its numbering. Accessing index 0 may not work:
<?php
$numbers = [5, 12, 8, 20];
$big = array_filter($numbers, fn ($number) => $number > 10);
echo implode(', ', array_keys($big)), "\n"; // 1, 3
$big = array_values($big);
echo $big[0]; // 12array_values() renumbers the array from zero.