Array Functions

PHP · Lesson 18 of 50 7 min read Updated

PHP comes with dozens of built-in functions for arrays. With them, a task that needs a ten-line loop, such as "give me the names of all students who passed, sorted by marks", often becomes two or three clear lines.

In this lesson you will learn the most useful ones: transforming, filtering and totalling arrays, searching them with the newer PHP 8.4 functions, sorting them, and pulling values out with destructuring. You should be comfortable with Arrays and arrow functions from Functions first.

Transform with array_map

array_map() runs a function on every item and returns a new array with the results. The original array is not changed. The callback comes first, then the array:

PHP
<?php
declare(strict_types=1);

$prices = ['Notebook' => 60, 'Pen' => 15, 'Bag' => 899];

$withGst = array_map(fn(int $price): float => round($price * 1.18, 2), $prices);

print_r($withGst);
Output
Array
(
    [Notebook] => 70.8
    [Pen] => 17.7
    [Bag] => 1060.82
)

When you pass one array, array_map() keeps its keys. The callback receives only the value, not the key.

Filter with array_filter

array_filter() keeps only the items for which the callback returns true. Here the array comes first, then the callback. Watch the keys in the result:

PHP
<?php
declare(strict_types=1);

$marks = [72, 28, 91, 30, 65];

$passed = array_filter($marks, fn(int $mark): bool => $mark >= 33);
print_r($passed);

$passed = array_values($passed);
print_r($passed);
Output
Array
(
    [0] => 72
    [2] => 91
    [4] => 65
)
Array
(
    [0] => 72
    [1] => 91
    [2] => 65
)

array_filter() keeps the original keys, so the result has gaps (0, 2, 4). This matters when you send the array as JSON: a list with gaps becomes a JSON object instead of a JSON list. Pass the result through array_values() when you need a clean list.

Total with array_reduce, array_sum and array_column

array_reduce() boils a whole array down to one value. The callback receives the running result (the carry) and the current item, and returns the new running result. The last argument is the starting value.

For the common jobs there are simpler tools. array_sum() adds up numbers, and array_column() pulls one field out of a list of records:

PHP
<?php
declare(strict_types=1);

$cart = [
    ['item' => 'Kurta', 'price' => 1299, 'qty' => 2],
    ['item' => 'Dupatta', 'price' => 499, 'qty' => 1],
    ['item' => 'Juttis', 'price' => 899, 'qty' => 1],
];

$total = array_reduce(
    $cart,
    fn(int $sum, array $line): int => $sum + $line['price'] * $line['qty'],
    0
);
echo "Cart total: ₹$total\n";

echo 'Items: ', array_sum(array_column($cart, 'qty')), "\n";
print_r(array_column($cart, 'price', 'item'));
Output
Cart total: ₹3996
Items: 4
Array
(
    [Kurta] => 1299
    [Dupatta] => 499
    [Juttis] => 899
)

With a third argument, array_column($cart, 'price', 'item') uses the item field as the key, which turns a list into a handy lookup table.

Search with array_find, array_any and array_all

PHP 8.4 added four functions that answer common questions about an array without a loop. Each one takes the array and a callback that receives the value and the key:

FunctionReturns
array_find($arr, $fn)The first value that matches, or null
array_find_key($arr, $fn)The key of the first match, or null
array_any($arr, $fn)true if at least one item matches
array_all($arr, $fn)true if every item matches
PHP
<?php
declare(strict_types=1);

$students = [
    ['name' => 'Aarav', 'city' => 'Rohtak', 'marks' => 81],
    ['name' => 'Meera', 'city' => 'Kochi', 'marks' => 94],
    ['name' => 'Kabir', 'city' => 'Jaipur', 'marks' => 67],
];

$topper = array_find($students, fn(array $s): bool => $s['marks'] > 90);
echo $topper['name'], "\n";

echo array_find_key($students, fn(array $s): bool => $s['city'] === 'Jaipur'), "\n";
var_dump(array_any($students, fn(array $s): bool => $s['marks'] < 70));
var_dump(array_all($students, fn(array $s): bool => $s['marks'] >= 33));
Output
Meera
2
bool(true)
bool(true)

These functions stop as soon as they know the answer. On PHP 8.3 or older, you would write a foreach loop with break instead. For a simple value search, in_array() and array_search() still work, always with true as the strict third argument.

Sorting

PHP's sort functions change the array in place and return true. Choose the function by what you sort on and whether keys must survive:

FunctionSorts byKeys
sort(), rsort()Value, up or downRenumbered 0, 1, 2
asort(), arsort()Value, up or downKept
ksort(), krsort()Key, up or downKept
usort()Your own comparisonRenumbered
uasort()Your own comparisonKept

For records, use usort() with the spaceship operator <=> from Operators. The comparison function returns a negative number, zero or a positive number, which is exactly what <=> gives. Swap $a and $b to sort in descending order:

PHP
<?php
declare(strict_types=1);

$students = [
    ['name' => 'Aarav', 'marks' => 81],
    ['name' => 'Meera', 'marks' => 94],
    ['name' => 'Kabir', 'marks' => 67],
    ['name' => 'Isha', 'marks' => 94],
];

usort($students, fn(array $a, array $b): int =>
    [$b['marks'], $a['name']] <=> [$a['marks'], $b['name']]
);

foreach ($students as $s) {
    echo "{$s['name']}: {$s['marks']}\n";
}
Output
Isha: 94
Meera: 94
Aarav: 81
Kabir: 67

Comparing two arrays with <=> compares their items in order. So this sorts by marks, highest first, and breaks ties by name in alphabetical order. That is how Isha comes before Meera.

Destructuring

Destructuring unpacks an array into separate variables in one line. Put square brackets on the left of =. For associative arrays, name the keys you want:

PHP
<?php
declare(strict_types=1);

[$firstName, $lastName] = explode(' ', 'Priya Sharma');
echo "$lastName, $firstName\n";

[, $month, $day] = explode('-', '2026-10-29');
echo "Day $day of month $month\n";

$order = ['id' => 4521, 'city' => 'Lucknow', 'total' => 1299];
['city' => $city, 'total' => $total] = $order;
echo "Order to $city: ₹$total\n";

foreach ([['Rohan', 88], ['Ananya', 95]] as [$name, $marks]) {
    echo "$name scored $marks\n";
}

$a = 'tea';
$b = 'coffee';
[$a, $b] = [$b, $a];
echo "$a, $b\n";
Output
Sharma, Priya
Day 29 of month 10
Order to Lucknow: ₹1299
Rohan scored 88
Ananya scored 95
coffee, tea

An empty spot, as in [, $month, $day], skips an item. Destructuring also works directly in foreach, and the last example swaps two variables without a temporary one. You may see list($a, $b) = ... in older code; it is the same thing.

Other handy functions

  • array_keys($arr) and array_values($arr) return just the keys or just the values.
  • array_merge($a, $b) joins arrays; later string keys overwrite earlier ones. [...$a, ...$b] does the same.
  • array_slice($arr, $offset, $length) returns part of an array.
  • array_unique($arr) removes duplicate values.
  • array_combine($keys, $values) builds an associative array from two lists.
  • range(1, 5) creates [1, 2, 3, 4, 5].

Common mistakes

  • Assigning the result of sort(). $sorted = sort($list); stores true. Sort functions change the array itself.
  • Forgetting that array_filter() keeps keys. Use array_values() before looping by index or encoding to JSON.
  • Mixing up argument order. array_map($callback, $array) but array_filter($array, $callback).
  • Using usort() when keys matter. It renumbers the keys; use uasort() to keep them.
  • Sorting mixed-case text. Uppercase letters sort before lowercase, so 'agra' comes after 'Pune'. Normalise the case first if that matters.

Key points

  • array_map() transforms every item; array_filter() keeps matching items but preserves keys.
  • array_reduce() combines items into one value; array_sum() and array_column() cover the common cases.
  • PHP 8.4's array_find(), array_find_key(), array_any() and array_all() replace many search loops.
  • Sort functions work in place; use usort() with <=> for records, and compare arrays to sort by several fields.
  • Destructuring with [$a, $b] = ... or ['key' => $var] = ... unpacks arrays into variables.
  • PHP 8.5 adds array_first() and array_last().

Exercise

You have a list of train journeys, each with train, from and fare keys: Shatabdi from Delhi at ₹1,245, Intercity from Rohtak at ₹185, Duronto from Pune at ₹2,310 and Passenger from Rohtak at ₹60. Use array_filter() to keep only journeys from Rohtak, usort() to sort them by fare from cheapest to dearest, and array_map() to build a list of strings like "Passenger: ₹60". Print the strings with implode(), then use array_any() to print whether any journey in the full list costs more than ₹2,000.

Show solution
PHP
<?php
declare(strict_types=1);

$journeys = [
    ['train' => 'Shatabdi', 'from' => 'Delhi', 'fare' => 1245],
    ['train' => 'Intercity', 'from' => 'Rohtak', 'fare' => 185],
    ['train' => 'Duronto', 'from' => 'Pune', 'fare' => 2310],
    ['train' => 'Passenger', 'from' => 'Rohtak', 'fare' => 60],
];

$fromRohtak = array_filter($journeys, fn(array $j): bool => $j['from'] === 'Rohtak');
usort($fromRohtak, fn(array $a, array $b): int => $a['fare'] <=> $b['fare']);
$labels = array_map(fn(array $j): string => "{$j['train']}: ₹{$j['fare']}", $fromRohtak);

echo implode(', ', $labels), "\n";
var_dump(array_any($journeys, fn(array $j): bool => $j['fare'] > 2000));
Output
Passenger: ₹60, Intercity: ₹185
bool(true)

usort() also renumbers the keys that array_filter() left behind. Each step returns or produces a new array, so the original $journeys list is unchanged when array_any() checks it.

Quick Quiz

1. What does $result = sort($names); store in $result?

2. array_filter([5, 50, 8, 80], fn($n) => $n > 10) returns which keys?

3. Which PHP 8.4 function returns true only when every item passes the test?

4. What does ['city' => $city] = ['name' => 'Isha', 'city' => 'Pune']; do?

Learn PHP with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call