In the Arrays lesson you stored and read the items of an array, one at a time or with foreach. Now Mrs. Tini asks for four things: only the dishes under $10, every price plus the packaging fee, the total of all prices, and a list sorted from the cheapest. Do you need four loops for four requests? No.
PHP has built-in functions (ready-made functions that come with PHP) that process every item of an array at once: filtering, changing, summarising and sorting. Most of these built-in functions take a small function called a callback. The callback says what to do with one item of the array. The built-in function runs that callback for every item, so you don't write a loop. The callback is usually an arrow function fn($price) => ... from the Functions lesson.
array_filter: filter, and the keys stay
This code keeps the prices under 10:
<?php
$prices = [15, 12, 5, 2, 7];
$cheap = array_filter($prices, fn($price) => $price < 10);
print_r($cheap);
Array
(
[2] => 5
[3] => 2
[4] => 7
)
The numbers on the left of the print_r result are the keys of the items. Look at those numbers, then guess: does echo $cheap[0] ?? "empty"; print 5 or empty? The answer is in the third point below.
array_filter($array, $callback)runs the callback for each item. When the callback answerstrue, the item goes into the result. When it answersfalse, the item is left out.- The result is a new array.
$pricesstill holds 5 prices. - The old keys come along. 5 stays at key 2, because that is where 5 sat in
$prices. So$cheap[0]doesn't exist, and$cheap[0] ?? "empty"printsempty. array_values($cheap)numbers the keys again from 0:[0] => 5,[1] => 2,[2] => 7.
array_map: change every item
This code adds 1 (the packaging fee) to every price:
<?php
$prices = [15, 12, 5];
$packaged = array_map(fn($price) => $price + 1, $prices);
print_r($packaged);
Array
(
[0] => 16
[1] => 13
[2] => 6
)
- The value the callback returns becomes the new item. The number of items is always the same as in the original array, and the keys stay the same.
- Its arguments come in the opposite order to
array_filter:array_maptakes the callback first, then the array.array_map($prices, fn...)is refused withTypeError: array_map(): Argument #1 ($callback) must be a valid callback or null.
Filtering and then changing can be combined in one line: array_map(fn($n) => $n * 2, array_filter($numbers, fn($n) => $n > 4)). array_filter runs first, then array_map changes its result. When $numbers holds [3, 7, 2, 9, 1, 5, 8], the result is [1] => 14, [3] => 18, [5] => 10, [6] => 16: the keys from array_filter are carried along.
array_reduce and array_sum: turn it into one value
This code adds up all the prices in two ways:
<?php
$prices = [15, 12, 5];
$total = array_reduce($prices, fn($carry, $price) => $carry + $price, 0);
echo $total . "\n"; // 32
echo array_sum($prices); // 32
$carryholds the result so far. The0at the end is its starting value.- On each round, the callback receives
$carryand the next item. The value it returns becomes the new$carry: 0 + 15 = 15, 15 + 12 = 27, 27 + 5 = 32. - If you only want to add numbers,
array_sumis shorter:array_sum([10, 20, 30])gives60.
Sorting: sort and usort
This code sorts three prices:
<?php
$prices = [15, 2, 7];
sort($prices);
echo $prices[0]; // 2
sort orders from small to large and changes the original array. It doesn't return a new array, only true. So $sorted = sort($prices); leaves $sorted holding true.
For a list of rows (arrays inside an array), use usort with a comparing callback, a callback that compares two items:
<?php
$menu = [
["name" => "Fried Rice", "price" => 15],
["name" => "Iced Tea", "price" => 5],
["name" => "Chicken Noodles", "price" => 12],
];
usort($menu, fn($a, $b) => $a["price"] <=> $b["price"]);
echo $menu[0]["name"]; // Iced Tea
<=>(the spaceship operator) compares two values: the result is-1when the left one is smaller,0when they are equal,1when the left one is bigger.usortuses that result to build the order.- To sort from the most expensive, swap it to
$b["price"] <=> $a["price"]. sortandusortboth renumber the keys from 0.
Careful with arrays keyed by name. In $prices from the Arrays lesson, the keys are the dish names. sort throws those names away, while asort keeps them:
<?php
$prices = ["Fried Rice" => 15, "Chicken Noodles" => 12, "Iced Tea" => 5];
$wrong = $prices;
sort($wrong);
// [5, 12, 15]: the dish names are gone
asort($prices);
// ["Iced Tea" => 5, "Chicken Noodles" => 12, "Fried Rice" => 15]
Other options for sorting are in this table. The versions with the letter r (reverse), such as arsort, sort from large to small.
| Function | Sorts by | Its keys | Pick it when |
|---|---|---|---|
sort / rsort |
value | renumbered from 0 | a plain list with no names |
asort / arsort |
value | kept | an array keyed by name, such as $prices |
ksort / krsort |
key | kept | dish names in alphabetical order |
usort / uasort |
your callback | usort renumbers, uasort keeps them |
your own rule, such as $menu above |
📌 array_column and spread
Two more tools, using $menu from the usort example above:
$priceByName = array_column($menu, "price", "name");
// ["Iced Tea" => 5, "Chicken Noodles" => 12, "Fried Rice" => 15]
$food = ["Fried Rice", "Chicken Noodles"];
$drinks = ["Iced Tea", "Orange Juice"];
$all = [...$food, ...$drinks]; // 4 dishes in one array
array_column takes one column (here "price") from every row. Its third argument ("name") makes another column the key. ... (spread) pours all the items of an array into a new array.
⚠️ Keys that are carried along, arguments in the wrong order
- Expecting
array_filter's result to be numbered 0, 1, 2. The old keys come along, so$result[0]may not exist.json_encode(a function that turns an array into JSON text) also writes it as an object{"2":5,"3":2,"4":7}, not as a list. Tidy it witharray_values. - Swapped argument order.
array_filter($array, $callback), butarray_map($callback, $array). $sorted = sort($prices);makes$sortedholdtrue.sortchanges$pricesitself.- Forgetting to store the result.
array_filter($prices, ...)on its own doesn't change$prices. Store it in a variable, such as$cheap = array_filter(...). array_filterwithout a callback drops every item that counts as false (as in the Control Flow lesson), including0and"0". So a dish with a stock of 0 disappears.
TL;DR: PHP's built-in functions can process every item of an array with no loop: you only give a callback, a small function that says what to do with one item. array_filter($array, fn($x) => condition) keeps the items that make the condition true, and keeps their old keys: the items are not numbered again. Tidy up with array_values. array_map(fn($x) => newValue, $array) changes every item, and the callback is written first. array_reduce($array, fn($carry, $x) => ..., 0) reduces the array to one value ($carry holds the result so far, starting at 0), and array_sum adds up directly. sort changes the original array and returns true. usort($array, fn($a, $b) => $a <=> $b) sorts with a comparing callback. Store the results of array_filter and array_map in a variable.
⚡ array_filter: the old keys come along
Write:
<?php
$prices = [15, 12, 5, 2, 7];
$cheap = array_filter($prices, fn($price) => $price < 10);
print_r($cheap);
Guess first: array_filter keeps 5, 2 and 7. Does echo $cheap[0] ?? "empty"; then print 5 or empty?
empty. The items it keeps still use their old keys: 5 stays at key 2, as in $prices. So $cheap[0] doesn't exist, and ?? uses "empty".
Meaning: array_filter runs the callback (the small function fn($price) => $price < 10) for each item of $prices, then keeps the items for which the callback answers true. The result is a new array, and each item keeps its old key. array_values numbers the keys again from 0.
⚡ array_map: the callback comes first
Write:
<?php
$prices = [15, 12, 5];
$packaged = array_map(fn($price) => $price + 1, $prices);
print_r($packaged);
Meaning: array_map runs the callback for each item of $prices. The value the callback returns becomes the new item: 16, 13, 6. Its arguments come in the opposite order to array_filter: the callback first, then the array.
⚡ sort changes the original array
Guess first: sort orders the items of an array from small to large. After $sorted = sort($prices);, what does $sorted hold?
true. sort doesn't return a new array. It orders $prices itself, from small to large.
Meaning: array_filter and array_map make a new array, so you need to store their result in a variable. sort is different: it changes the original array directly.