CodeMIRAI
0 XP

Array functions

2 min read 7 runnable examples Quiz included

PHP has dozens of array functions. A handful of them replace most of the loops you'd otherwise write.

array_map: transform every element

PHP
<?php
$prices = [100, 250, 80];
$withTax = array_map(fn($p) => round($p * 1.18, 2), $prices);
print_r($withTax);

$names = ["asha", "leo"];
print_r(array_map("ucfirst", $names));      // a built-in function by name

array_filter: keep some elements

PHP
<?php
$scores = [72, 45, 88, 91, 38];
$passed = array_filter($scores, fn($s) => $s >= 50);
print_r($passed);
print_r(array_values($passed));             // renumber from 0

$stock = ["apples" => 40, "cherries" => 0, "dates" => 12];
print_r(array_filter($stock));              // no callback: drops falsy values

array_filter keeps the original keys, which leaves gaps in a numbered array; wrap it in array_values when you want a clean list.

array_reduce: boil down to one value

PHP
<?php
$cart = [["item" => "Pen", "price" => 30, "qty" => 3], ["item" => "Bag", "price" => 799, "qty" => 1]];
$total = array_reduce($cart, fn($sum, $line) => $sum + $line["price"] * $line["qty"], 0);
echo "Total: $total\n";

array_reduce walks through the array, carrying a running result ($sum) from one element to the next, starting from the last argument, here 0.

Sorting with your own rule: usort

PHP
<?php
$people = [
    ["name" => "Leo", "age" => 30],
    ["name" => "Asha", "age" => 21],
    ["name" => "Mei", "age" => 24],
];
usort($people, fn($a, $b) => $a["age"] <=> $b["age"]);
echo implode(", ", array_column($people, "name")), "\n";

usort($people, fn($a, $b) => strcmp($a["name"], $b["name"]));
echo implode(", ", array_column($people, "name")), "\n";

usort sorts with a comparison function returning a negative number, zero or a positive number. The spaceship operator <=> produces exactly that.

Columns, keys and values

PHP
<?php
$products = [
    ["id" => 7, "name" => "Keyboard", "price" => 89],
    ["id" => 9, "name" => "Mouse", "price" => 25],
];
print_r(array_column($products, "name"));            // one column
print_r(array_column($products, "price", "name"));   // name => price
print_r(array_combine(["a", "b"], [1, 2]));          // keys + values
print_r(array_flip(["red" => 1, "blue" => 2]));      // swap keys and values

Unique values, slices and merging

PHP
<?php
print_r(array_unique([3, 1, 3, 2, 1]));
print_r(array_slice(["a", "b", "c", "d", "e"], 1, 3));   // from index 1, take 3

$defaults = ["theme" => "light", "lang" => "en"];
$chosen = ["theme" => "dark"];
print_r(array_merge($defaults, $chosen));    // later arrays win
print_r($chosen + $defaults);                // + keeps the FIRST value for each key

array_merge and + both combine arrays, but array_merge lets later values overwrite earlier ones, while + keeps the first. Both are handy for applying defaults to settings.

Putting them together

PHP
<?php
$orders = [
    ["customer" => "Asha", "total" => 1200, "status" => "paid"],
    ["customer" => "Leo", "total" => 300, "status" => "refunded"],
    ["customer" => "Mei", "total" => 850, "status" => "paid"],
    ["customer" => "Asha", "total" => 400, "status" => "paid"],
];

$paid = array_filter($orders, fn($o) => $o["status"] === "paid");
$revenue = array_sum(array_column($paid, "total"));
$customers = array_unique(array_column($paid, "customer"));

echo "Paid revenue: $revenue\n";
echo "Paying customers: ", implode(", ", $customers), "\n";

Filter, pick a column, sum or de-duplicate: a pipeline of small functions answers the question with no loop in sight.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.