array_map, filter, reduce
array_map
Function array_map builds a new array by applying a callback to every item. The input stays unchanged and the output has the same length.
Arrow functions keep the call short. Use them for pure transforms like trimming or uppercasing.
$names = ["anna", "bob"]; $upper = array_map(fn($v) => strtoupper($v), $names); print_r($upper);
array_filter
Function array_filter keeps only items where the callback returns true. Without a callback it drops falsy values like zero and empty string.
Remember that keys survive filtering, so reindex with array_values when order without gaps matters.
$nums = [1, 2, 3, 4]; $even = array_filter($nums, fn($v) => $v % 2 === 0); print_r(array_values($even));
array_reduce
Function array_reduce folds a list into a single value like a sum or a string. The carry holds the running result while each item updates it.
Always set the starting value explicitly so empty arrays return a sane default instead of null.
$nums = [1, 2, 3]; $sum = array_reduce($nums, fn($c, $v) => $c + $v, 0); echo $sum;
array_column
Function array_column pulls one field out of a list of rows. It is ideal for turning query results into plain lists of names or ids.
Pass a second field name to index the result by id and get fast lookup without loops.
$users = [["id" => 1, "name" => "Ann"], ["id" => 2, "name" => "Bob"]]; print_r(array_column($users, "name")); print_r(array_column($users, "name", "id"));
Автор статьи: Arthur Isaev