PHP Array Functions

Transform, filter, sort and summarise arrays with PHP's built-in functions: array_map, array_filter, array_reduce, usort, array_column, array_slice and more.

Lesson 7 of 86Intermediate17 min read

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:

PHP
$prices = [10, 25, 40];
$withTax = array_map(fn($p) => $p * 1.2, $prices);   // [12, 30, 48]
  • fn($p) => expression is 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 needs use ($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:

PHP
$total = array_reduce($basket, fn($sum, $item) => $sum + $item['price'] * $item['qty'], 0);

Sorting arrays of records

FunctionSorts byKeeps keys?
sort / rsortValue, up / downNo
asort / arsortValue, up / downYes
ksort / krsortKey, up / downYes
usort($a, callback)Your own comparisonNo

For arrays of records, use usort with the spaceship operator <=>, which returns -1, 0 or 1:

PHP
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) and array_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_map transforms every item; array_filter keeps items that pass a test; array_reduce combines them into one value.
  • Arrow functions fn($x) => ... make callbacks short and can read outside variables.
  • usort with <=> sorts arrays of records; sort functions change the array in place.
  • array_column pulls one field from every record; array_slice takes part of an array.
  • array_filter keeps keys, so use array_values to renumber the result.

PHP Array Functions Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Shop data with map, filter and reduce

PHP
<?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";
Output
NOTEBOOK, BACKPACK, DESK LAMP
Stock value: £1,483.85
Kept keys: 0, 2, 3
Line-by-line explanation
  1. Line 9Keep only products with stock left.
  2. Line 10Turn each remaining product into its name in capitals.
  3. Line 13Start at 0 and add each product's price times stock.
  4. Lines 16 to 17array_filter kept the original keys, so key 1 is missing. Use array_values to renumber.
Example 2

Sorting and a top 3

PHP
<?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";
Output
1. Ben (340)
2. Cleo (340)
3. Eli (210)
Lowest: Dev
Line-by-line explanation
  1. Line 10Comparing arrays with <=> compares item by item: score descending first ($b before $a), then name ascending to break ties.
  2. Line 12array_slice takes the first three after sorting.
  3. Line 16end() gives the last item of the sorted array.
Example 3

Columns, lookups and merging

PHP
<?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);
Output
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
  1. Line 8Pull the email field out of every user.
  2. Line 11The third argument chooses the keys, building an id-to-name lookup.
  3. Line 14array_unique drops the second "Ana".
  4. 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

Don't
$sorted = sort($prices);      // $sorted is true
Do
sort($prices);                // $prices itself is now sorted

Gaps after array_filter

Don't
$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
Do
$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

Don't
array_map($prices, fn($p) => $p * 2);       // TypeError
Do
array_map(fn($p) => $p * 2, $prices);        // callback first
array_filter($prices, fn($p) => $p > 5);     // array first

array_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.

Fill in the blankseasy

Complete the code so every price is doubled.

$doubled = (fn($p) => $p * 2, $prices);
Predict the outputeasy

What does this print?

$n = array_filter([5, 0, 8, 0, 3]);
echo count($n);
Predict the outputmedium

What does this print?

echo array_reduce([2, 3, 4], fn($c, $x) => $c * $x, 1);
Multiple choicemedium

Which sorts products by price, cheapest first?

Multiple choicehard

What does array_column($rows, 'name', 'id') return?

PHP Array Functions Quiz

5 questions to check what you learned.

  1. Which function keeps only the items that pass a test?

    • array_map
    • array_filter
    • array_reduce
    • array_slice
  2. What does 5 <=> 3 return?

    • -1
    • 0
    • true
    • 1
  3. What is fn($x) => $x + 1?

    • A loop
    • An array
    • An arrow function that returns $x + 1
    • A comparison
  4. Why use array_values after array_filter?

    • To sort the result
    • To remove duplicates
    • To renumber the keys from 0
    • To convert to JSON
  5. What does array_slice($a, 2) return for $a = ['x', 'y', 'z', 'w']?

    • ['x', 'y']
    • ['z', 'w']
    • ['y', 'z', 'w']
    • ['z']