Advanced Arrays — PHP

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…

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_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
)

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

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

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

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.

What you will learn