Arrays are the workhorse of PHP. Rows from a database, decoded JSON, form submissions and lists of products all arrive as arrays, often as arrays of arrays. Much of a PHP developer's day is spent reshaping them: picking out the products in stock, sorting by price, adding up a basket, pulling every email from a list of users.
You could write a foreach loop for each job, and in the arrays lesson you met a few helpers like in_array and sort. PHP has dozens more functions that turn those loops into single, readable lines. Each one does one job, and they combine neatly.
In this lesson you'll transform arrays with array_map, keep matching items with array_filter, combine values with array_reduce, sort arrays of records with usort, and pull out, slice, merge and de-duplicate data. You'll also use arrow functions, the short fn syntax that makes these functions especially concise.
Arrow functions and array_map
Many array functions take a callback: a function to run on each item. PHP 7.4's arrow functions make callbacks short:
$prices = [10, 25, 40];
$withTax = array_map(fn($p) => $p * 1.2, $prices); // [12, 30, 48]fn($p) => expressionis a one-line function that returns the expression.- Arrow functions can read variables from the surrounding code automatically, such as
fn($p) => $p * $rate. array_map(callback, $array)returns a new array with the callback applied to every item. The original is unchanged.- Older code uses
function($p) { return $p * 1.2; }, which needsuse ($rate)to read outside variables.
array_filter and array_reduce
array_filter($array, callback) keeps only the items for which the callback returns true. Without a callback, it removes "empty" values such as "", 0 and null.
It keeps the original keys, so filtering [0 => "a", 1 => "", 2 => "b"] gives keys 0 and 2. Wrap the result in array_values() to renumber it from 0, which matters before converting to JSON.
array_reduce($array, callback, start) combines all items into one value. The callback receives the running total so far and the current item:
$total = array_reduce($basket, fn($sum, $item) => $sum + $item['price'] * $item['qty'], 0);Sorting arrays of records
| Function | Sorts by | Keeps keys? |
|---|---|---|
sort / rsort | Value, up / down | No |
asort / arsort | Value, up / down | Yes |
ksort / krsort | Key, up / down | Yes |
usort($a, callback) | Your own comparison | No |
For arrays of records, use usort with the spaceship operator <=>, which returns -1, 0 or 1:
usort($products, fn($a, $b) => $a['price'] <=> $b['price']);Swap $a and $b for descending order. All sort functions change the array in place and return true, not the sorted array.
Picking, slicing and combining
array_column($rows, 'email')pulls one field out of every record;array_column($rows, 'name', 'id')builds an id-to-name lookup.array_slice($a, 0, 3)returns the first three items, which is handy for "top 3" lists.array_merge($a, $b)or[...$a, ...$b]joins arrays.array_unique($a)removes duplicate values.array_keys($a)andarray_values($a)return just the keys or just the values.array_combine($keys, $values)pairs two arrays into one associative array.
PHP Array Functions Syntax
Array functions
array_map(fn($x) => $x * 2, $a);
array_filter($a, fn($x) => $x > 0);
array_reduce($a, fn($carry, $x) => $carry + $x, 0);
usort($a, fn($x, $y) => $x['price'] <=> $y['price']);
array_column($rows, 'name', 'id');
array_slice($a, 0, 3);
[...$a, ...$b]; array_merge($a, $b);
array_unique($a); array_values($a); array_keys($a);PHP Array Functions Summary
array_maptransforms every item;array_filterkeeps items that pass a test;array_reducecombines them into one value.- Arrow functions
fn($x) => ...make callbacks short and can read outside variables. usortwith<=>sorts arrays of records; sort functions change the array in place.array_columnpulls one field from every record;array_slicetakes part of an array.array_filterkeeps keys, so usearray_valuesto renumber the result.
PHP Array Functions Examples
Each example shows the code, the output it produces and what each part does.
Shop data with map, filter and reduce
<?php
$products = [
['name' => 'Notebook', 'price' => 3.50, 'stock' => 120],
['name' => 'Lunch box', 'price' => 8.75, 'stock' => 0],
['name' => 'Backpack', 'price' => 34.99, 'stock' => 15],
['name' => 'Desk lamp', 'price' => 24.50, 'stock' => 22],
];
$inStock = array_filter($products, fn($p) => $p['stock'] > 0);
$names = array_map(fn($p) => strtoupper($p['name']), $inStock);
echo implode(", ", $names) . "\n";
$stockValue = array_reduce($products, fn($sum, $p) => $sum + $p['price'] * $p['stock'], 0);
echo "Stock value: £" . number_format($stockValue, 2) . "\n";
$keys = array_keys($inStock);
echo "Kept keys: " . implode(", ", $keys) . "\n";NOTEBOOK, BACKPACK, DESK LAMP
Stock value: £1,483.85
Kept keys: 0, 2, 3Line-by-line explanation
- Line 9Keep only products with stock left.
- Line 10Turn each remaining product into its name in capitals.
- Line 13Start at 0 and add each product's price times stock.
- Lines 16 to 17array_filter kept the original keys, so key 1 is missing. Use array_values to renumber.
Sorting and a top 3
<?php
$players = [
['name' => 'Ana', 'score' => 120],
['name' => 'Ben', 'score' => 340],
['name' => 'Cleo', 'score' => 340],
['name' => 'Dev', 'score' => 90],
['name' => 'Eli', 'score' => 210],
];
usort($players, fn($a, $b) => [$b['score'], $a['name']] <=> [$a['score'], $b['name']]);
$top3 = array_slice($players, 0, 3);
foreach ($top3 as $i => $p) {
echo ($i + 1) . ". {$p['name']} ({$p['score']})\n";
}
echo "Lowest: " . end($players)['name'] . "\n";1. Ben (340)
2. Cleo (340)
3. Eli (210)
Lowest: DevLine-by-line explanation
- Line 10Comparing arrays with <=> compares item by item: score descending first ($b before $a), then name ascending to break ties.
- Line 12array_slice takes the first three after sorting.
- Line 16end() gives the last item of the sorted array.
Columns, lookups and merging
<?php
$users = [
['id' => 7, 'name' => 'Ana', 'email' => 'ana@example.com'],
['id' => 12, 'name' => 'Ben', 'email' => 'ben@example.com'],
['id' => 15, 'name' => 'Ana', 'email' => 'ana.k@example.com'],
];
$emails = array_column($users, 'email');
echo implode("; ", $emails) . "\n";
$byId = array_column($users, 'name', 'id');
echo "User 12 is {$byId[12]}\n";
$names = array_unique(array_column($users, 'name'));
echo "Unique names: " . implode(", ", $names) . "\n";
$admins = ['root', 'Ana'];
$everyone = array_values(array_unique([...$admins, ...$names]));
print_r($everyone);ana@example.com; ben@example.com; ana.k@example.com
User 12 is Ben
Unique names: Ana, Ben
Array
(
[0] => root
[1] => Ana
[2] => Ben
)Line-by-line explanation
- Line 8Pull the email field out of every user.
- Line 11The third argument chooses the keys, building an id-to-name lookup.
- Line 14array_unique drops the second "Ana".
- Line 18The spread operator joins two arrays; array_unique and array_values tidy the result.
Common PHP Array Functions Mistakes
Expecting sort() to return the sorted array
$sorted = sort($prices); // $sorted is truesort($prices); // $prices itself is now sortedGaps after array_filter
$even = array_filter([1, 2, 3, 4], fn($n) => $n % 2 === 0);
echo json_encode($even); // {"1":2,"3":4} an object, not a list$even = array_values(array_filter([1, 2, 3, 4], fn($n) => $n % 2 === 0));
echo json_encode($even); // [2,4]Arguments in the wrong order
array_map($prices, fn($p) => $p * 2); // TypeErrorarray_map(fn($p) => $p * 2, $prices); // callback first
array_filter($prices, fn($p) => $p > 5); // array firstarray_map takes the callback first; array_filter and array_reduce take the array first.
PHP Array Functions in Real Projects
Array functions in PHP apps
Controllers in web applications filter and sort database results before showing them, APIs reshape arrays with array_map before calling json_encode, and reports total columns with array_sum and array_reduce. Laravel's Collection class wraps these same ideas in chainable methods like ->filter()->map()->sortBy(), so learning the plain functions makes frameworks easier to understand.
PHP Array Functions FAQ
Should I use array_map or foreach?
Use array_map when you're turning one array into another of the same length, such as adding tax to every price; the intent is clear and there's no temporary array to manage. Use foreach when the loop does several things, needs break, or updates more than one variable.
What is the difference between array_merge and the + operator?
array_merge appends lists and renumbers numeric keys, and for string keys the later value wins. The + operator keeps the left array's keys and only adds keys that are missing, so [1, 2] + [5, 6, 7] gives [1, 2, 7]. Use array_merge or spread syntax to join lists, and + to fill in default settings.
How do I sort an array of records by two fields?
Compare arrays with the spaceship operator inside usort: usort($rows, fn($a, $b) => [$a['city'], $a['name']] <=> [$b['city'], $b['name']]);. PHP compares the first elements, and only looks at the second when the first are equal.
How do I filter an array by its keys?
Pass the ARRAY_FILTER_USE_KEY flag: array_filter($settings, fn($key) => str_starts_with($key, 'mail_'), ARRAY_FILTER_USE_KEY). With ARRAY_FILTER_USE_BOTH, the callback receives the value and the key.
How do I find the highest value of one field in a list of records?
Pull the field out with array_column and pass it to max: max(array_column($products, 'price')). To get the whole record rather than just the value, sort with usort and take the first item, or loop once while keeping the best record seen so far.
PHP Array Functions Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code so every price is doubled.
$doubled = (fn($p) => $p * 2, $prices);
What does this print?
$n = array_filter([5, 0, 8, 0, 3]);
echo count($n);
What does this print?
echo array_reduce([2, 3, 4], fn($c, $x) => $c * $x, 1);
Which sorts products by price, cheapest first?
What does array_column($rows, 'name', 'id') return?
PHP Array Functions Quiz
5 questions to check what you learned.
Which function keeps only the items that pass a test?
- array_map
- array_filter
- array_reduce
- array_slice
What does
5 <=> 3return?- -1
- 0
- true
- 1
What is
fn($x) => $x + 1?- A loop
- An array
- An arrow function that returns $x + 1
- A comparison
Why use array_values after array_filter?
- To sort the result
- To remove duplicates
- To renumber the keys from 0
- To convert to JSON
What does
array_slice($a, 2)return for$a = ['x', 'y', 'z', 'w']?- ['x', 'y']
- ['z', 'w']
- ['y', 'z', 'w']
- ['z']