Array Functions

PHP has around eighty built-in array functions. A handful of them — array_map, array_filter, array_reduce, array_column and the new array_find family — replace most hand-written loops with clear one-liners. This lesson covers those and other everyday helpers.

array_map: transform every element

array_map calls a function on each element and returns a new array of the results. Arrow functions (fn($x) => …, lesson 31) make it compact:

PHP
<?php

$prices = [10, 25, 40];
$withTax = array_map(fn($p) => $p * 1.2, $prices);
echo implode(", ", $withTax), "\n";

$names = ["ana", "ben", "cleo"];
echo implode(", ", array_map('ucfirst', $names)), "\n";
echo implode(", ", array_map(strtoupper(...), $names)), "\n";

$labels = array_map(fn($n, $p) => "$n: $p", ["A", "B"], [1, 2]);   // several arrays
echo implode(" | ", $labels), "\n";
Output
12, 30, 48
Ana, Ben, Cleo
ANA, BEN, CLEO
A: 1 | B: 2

A function can be passed by name as a string ('ucfirst') or with the first-class callable syntax strtoupper(...). array_map keeps string keys when given a single array.

array_filter: keep some elements

array_filter keeps the elements for which the function returns true. Without a function, it removes all falsy values:

PHP
<?php

$numbers = [5, 12, 8, 21, 3, 16];
$big = array_filter($numbers, fn($n) => $n > 10);
print_r($big);
print_r(array_values($big));

print_r(array_filter(["a", "", null, "0", "b", 0]));

$stock = ["apples" => 12, "pears" => 0, "plums" => 7];
print_r(array_filter($stock, fn($qty, $fruit) => $qty > 0 && $fruit !== "plums", ARRAY_FILTER_USE_BOTH));
Output
Array
(
    [1] => 12
    [3] => 21
    [5] => 16
)
Array
(
    [0] => 12
    [1] => 21
    [2] => 16
)
Array
(
    [0] => a
    [4] => b
)
Array
(
    [apples] => 12
)

array_filter keeps the original keys, which leaves gaps in a list. Wrap it in array_values when you need a clean 0, 1, 2… list (for example before encoding JSON).

array_reduce: combine into one value

PHP
<?php

$cart = [
    ["name" => "Pen", "price" => 1.20, "qty" => 10],
    ["name" => "Notebook", "price" => 3.50, "qty" => 4],
];

$total = array_reduce($cart, fn($sum, $item) => $sum + $item["price"] * $item["qty"], 0);
echo $total, "\n";

$longest = array_reduce(["fig", "banana", "kiwi"], fn($best, $w) => strlen($w) > strlen($best) ? $w : $best, "");
echo $longest, "\n";
Output
26
banana

The function receives the running result and the next element; the last argument is the starting value. For simple sums, array_sum and array_product are clearer.

Finding elements (PHP 8.4)

array_find returns the first element that matches, array_find_key its key, and array_any/array_all answer yes/no questions — all without writing a loop:

PHP
<?php

$users = [
    ["name" => "Ana", "age" => 34, "admin" => false],
    ["name" => "Ben", "age" => 17, "admin" => false],
    ["name" => "Cleo", "age" => 41, "admin" => true],
];

echo array_find($users, fn($u) => $u["admin"])["name"], "\n";
var_dump(array_find_key($users, fn($u) => $u["age"] < 18));
var_dump(array_find($users, fn($u) => $u["age"] > 90));
var_dump(array_any($users, fn($u) => $u["age"] < 18));
var_dump(array_all($users, fn($u) => $u["age"] > 0));
Output
Cleo
int(1)
NULL
bool(true)
bool(true)

array_column: pull out one field

When you have a list of rows (like database results), array_column extracts one field from each — optionally keyed by another field:

PHP
<?php

$products = [
    ["id" => 7, "name" => "Lamp", "price" => 34.5],
    ["id" => 9, "name" => "Desk", "price" => 249.0],
    ["id" => 12, "name" => "Chair", "price" => 129.0],
];

echo implode(", ", array_column($products, "name")), "\n";
print_r(array_column($products, "price", "id"));
echo max(array_column($products, "price")), "\n";
Output
Lamp, Desk, Chair
Array
(
    [7] => 34.5
    [9] => 249
    [12] => 129
)
249

Keys, values and combinations

PHP
<?php

$keys = ["name", "city"];
$values = ["Lin", "Oslo"];
print_r(array_combine($keys, $values));

print_r(array_fill_keys(["a", "b"], 0));
print_r(array_unique([3, 1, 3, 2, 1]));
print_r(array_chunk([1, 2, 3, 4, 5], 2));
Output
Array
(
    [name] => Lin
    [city] => Oslo
)
Array
(
    [a] => 0
    [b] => 0
)
Array
(
    [0] => 3
    [1] => 1
    [3] => 2
)
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 3
            [1] => 4
        )

    [2] => Array
        (
            [0] => 5
        )

)

Set operations

PHP
<?php

$alice = ["php", "sql", "git", "css"];
$bob = ["git", "java", "php", "docker"];

echo implode(", ", array_intersect($alice, $bob)), "\n";
echo implode(", ", array_diff($alice, $bob)), "\n";
echo implode(", ", array_unique([...$alice, ...$bob])), "\n";

$defaults = ["a" => 1, "b" => 2, "c" => 3];
print_r(array_diff_key($defaults, ["b" => true]));
Output
php, git
sql, css
php, sql, git, css, java, docker
Array
(
    [a] => 1
    [c] => 3
)

Chaining operations

Real code combines these functions. PHP 8.5's pipe operator |> (lesson 31) lets you write the steps in reading order:

PHP
<?php

$orders = [
    ["customer" => "Ana", "total" => 120.0, "status" => "paid"],
    ["customer" => "Ben", "total" => 45.5, "status" => "cancelled"],
    ["customer" => "Cleo", "total" => 310.0, "status" => "paid"],
    ["customer" => "Dev", "total" => 89.9, "status" => "paid"],
];

$paidTotals = array_column(array_filter($orders, fn($o) => $o["status"] === "paid"), "total");
echo array_sum($paidTotals), "\n";

$bigSpenders = $orders
    |> (fn($os) => array_filter($os, fn($o) => $o["total"] > 100))
    |> (fn($os) => array_column($os, "customer"))
    |> (fn($names) => implode(" & ", $names));
echo $bigSpenders, "\n";
Output
519.9
Ana & Cleo

Try it yourself

From a list of students, print the names of those who passed (50 or more), sorted, plus the class average.

Try it yourself · main.php
Edit the code, copy it into main.php, then run it with php main.php (PHP 8.5). How to install PHP
Output
Passed: Asha, Dev, Finn
Average: 62.2