TExcelTAD
Home › PHP › PHP Array Functions

PHP Array Functions

PHP has more than 70 built-in array functions. You do not need to memorise them all — but a dozen of them will replace most of the loops you would otherwise write by hand. This lesson groups the most useful ones by job.

Transform, filter, reduce

These three are the workhorses of data processing. Each takes a callback — a function that is applied to the items.

Function Returns Callback receives
array_map($fn, $a) a new array with $fn applied to every value the value
array_filter($a, $fn) only the items for which $fn returns true (keys kept) the value
array_reduce($a, $fn, $start) a single value built up item by item the running result and the value

Note the argument order: array_map takes the callback first, array_filter and array_reduce take the array first.

php · try it yourself
<?php
$prices = [12.5, 8, 30, 4.25];

$withTax = array_map(fn($p) => round($p * 1.1, 2), $prices);
echo implode(' | ', $withTax) . PHP_EOL;

$expensive = array_filter($prices, fn($p) => $p >= 10);
print_r($expensive);

$total = array_reduce($prices, fn($sum, $p) => $sum + $p, 0);
echo "Total: $total" . PHP_EOL;
13.75 | 8.8 | 33 | 4.68
Array
(
    [0] => 12.5
    [2] => 30
)
Total: 54.75

array_filter() keeps the original keys (0 and 2 above). Wrap it in array_values() if you need a clean list. Called without a callback, it removes every "falsy" value (0, '', null, false, []).

Tip: Pass ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH as the third argument to array_filter() to filter by key, or by key and value.

Combining and splitting

php · try it yourself
<?php
$keys = ['id', 'name', 'city'];
$values = [7, 'Hoa', 'Hue'];
$person = array_combine($keys, $values);
print_r($person);

$batches = array_chunk([1, 2, 3, 4, 5], 2);
echo json_encode($batches) . PHP_EOL;

$a = ['red', 'green', 'blue'];
$b = ['green', 'yellow'];
echo 'Merged: ' . implode(',', array_merge($a, $b)) . PHP_EOL;
echo 'Unique: ' . implode(',', array_unique(array_merge($a, $b))) . PHP_EOL;
echo 'Common: ' . implode(',', array_intersect($a, $b)) . PHP_EOL;
echo 'Only in a: ' . implode(',', array_diff($a, $b)) . PHP_EOL;
Array
(
    [id] => 7
    [name] => Hoa
    [city] => Hue
)
[[1,2],[3,4],[5]]
Merged: red,green,blue,green,yellow
Unique: red,green,blue,yellow
Common: green
Only in a: red,blue
Function What it does
array_merge($a, $b, …) join arrays (lists are appended, string keys overwritten)
array_combine($keys, $values) build an associative array from two lists
array_chunk($a, $size) split into pieces of $size
array_unique($a) remove duplicate values
array_diff($a, $b) values of $a that are not in $b
array_intersect($a, $b) values present in both
array_fill_keys($keys, $v) new array with every key set to $v

Searching and checking

php · try it yourself
<?php
$inventory = ['bolt' => 120, 'nut' => 0, 'screw' => 45, 'washer' => 0];

var_dump(in_array(45, $inventory));
var_dump(array_search(0, $inventory));
echo 'Out of stock: ' . implode(', ', array_keys($inventory, 0)) . PHP_EOL;

$firstBig = array_find($inventory, fn($qty) => $qty > 100);
echo "First big stock: $firstBig" . PHP_EOL;

var_dump(array_any($inventory, fn($qty) => $qty === 0));
var_dump(array_all($inventory, fn($qty) => $qty >= 0));
bool(true)
string(3) "nut"
Out of stock: nut, washer
First big stock: 120
bool(true)
bool(true)

array_find(), array_find_key(), array_any() and array_all() are new in PHP 8.4. On older versions you would write a small foreach loop instead.

Note: in_array() and array_search() use loose comparison by default ('1' == 1). Pass true as the third argument for strict comparison: in_array('1', [1, 2], true) is false.

Destructuring arrays

Square brackets on the left side of = unpack an array into variables. It works with keys too, and inside foreach.

php · try it yourself
<?php
[$first, , $third] = ['alpha', 'beta', 'gamma'];
echo "$first and $third" . PHP_EOL;

['w' => $width, 'h' => $height] = ['w' => 1920, 'h' => 1080];
echo "{$width}x{$height}" . PHP_EOL;

$points = [[0, 0], [3, 4]];
foreach ($points as [$x, $y]) {
    echo "($x, $y) distance " . sqrt($x ** 2 + $y ** 2) . PHP_EOL;
}

[$a, $b] = [1, 2];
[$a, $b] = [$b, $a]; // swap
echo "a=$a b=$b" . PHP_EOL;

$parts = [...['x', 'y'], ...['z']]; // spread
echo implode('', $parts) . PHP_EOL;
alpha and gamma
1920x1080
(0, 0) distance 0
(3, 4) distance 5
a=2 b=1
xyz

More to explore

Function Purpose
array_sum() / array_product() add / multiply all values
array_count_values($a) how many times each value occurs
array_pad($a, $n, $v) grow to $n items
array_walk($a, $fn) run $fn on every item (can modify by reference)
compact('a', 'b') / extract($arr) variables ↔ array
max($a) / min($a) largest / smallest value

Test yourself

Which call keeps only even numbers from $n?

  1. array_map($n, fn($x) => $x % 2 == 0)
  2. array_filter($n, fn($x) => $x % 2 == 0)
  3. array_reduce($n, fn($x) => $x % 2)
  4. array_search(2, $n)

What does array_diff(['a', 'b', 'c'], ['b']) contain?

  1. ['b']
  2. ['a', 'c'] (keys 0 and 2)
  3. ['a', 'b', 'c']
  4. An empty array

Which of these functions was added in PHP 8.4?

  1. array_map()
  2. array_column()
  3. array_find()
  4. array_chunk()