Skip to main content

Lesson 4 of 8

Array Functions - map, filter, reduce & Sort

PHP's array functions enable functional-style data processing without explicit loops. array_map transforms, array_filter selects, array_reduce aggregates. Understanding these removes repetitive foreach loops and makes data pipelines readable and testable.

15 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Functional Array Processing

Functional Array Processing
<?php
declare(strict_types=1);

$posts = [
    ["id" => 1, "title" => "PHP Basics",   "views" => 500,  "published" => true],
    ["id" => 2, "title" => "PDO Guide",    "views" => 1200, "published" => true],
    ["id" => 3, "title" => "PHP Security", "views" => 800,  "published" => false],
    ["id" => 4, "title" => "PHP 8 Match",  "views" => 300,  "published" => true],
];

// ── array_map - transform every element ──────────────────────
// Returns SAME length array with each element transformed
$titles = array_map(fn($p) => strtoupper($p["title"]), $posts);
// ["PHP BASICS", "PDO GUIDE", "PHP SECURITY", "PHP 8 MATCH"]

// Add a calculated field to each element
$withRating = array_map(function($post) {
    $post["rating"] = match(true) {
        $post["views"] >= 1000 => "hot",
        $post["views"] >= 500  => "warm",
        default                => "cold",
    };
    return $post;
}, $posts);

// ── array_filter - keep matching elements ─────────────────────
// Returns array with non-matching elements removed (preserve keys)
$published = array_filter($posts, fn($p) => $p["published"] === true);
$popular   = array_filter($posts, fn($p) => $p["views"] > 700);

// Reindex after filter (filter preserves original keys)
$published = array_values($published);  // re-index to 0,1,2,...

// Filter without callback - removes falsy values
$mixed  = [0, 1, "", "hello", null, false, true, []];
$truthy = array_filter($mixed);   // [1, "hello", true]

// ── array_reduce - fold to a single value ────────────────────
$totalViews = array_reduce($posts, fn($carry, $post) => $carry + $post["views"], 0);
// 500 + 1200 + 800 + 300 = 2800

$byId = array_reduce($posts, function($carry, $post) {
    $carry[$post["id"]] = $post;
    return $carry;
}, []);
// Transform array of posts into id => post map - very useful for lookups

// ── Sorting ──────────────────────────────────────────────────
$nums = [3, 1, 4, 1, 5, 9, 2];
sort($nums);     // [1, 1, 2, 3, 4, 5, 9] - reindexes
rsort($nums);    // [9, 5, 4, 3, 2, 1, 1] - reverse sort

$assoc = ["b" => 2, "a" => 1, "c" => 3];
asort($assoc);   // sort by value, preserve keys: [a=>1, b=>2, c=>3]
ksort($assoc);   // sort by key: [a=>1, b=>2, c=>3]

// usort - custom sort with comparator (modifies array in place)
usort($posts, fn($a, $b) => $b["views"] <=> $a["views"]);  // desc by views
uasort($posts, fn($a, $b) => strcmp($a["title"], $b["title"]));  // by title, keep keys

// ── array_column - extract column from multi-dimensional ──────
$ids    = array_column($posts, "id");      // [1, 2, 3, 4]
$titles = array_column($posts, "title");   // ["PHP Basics", ...]

// Index by a key - very powerful for lookups
$indexed = array_column($posts, null, "id");
// [1 => ["id"=>1, "title"=>...], 2 => [...], ...]
echo $indexed[2]["title"];   // "PDO Guide"

// ── array_walk - apply function to each element in-place ─────
array_walk($posts, function(&$post, $key) {
    $post["slug"] = strtolower(str_replace(" ", "-", $post["title"]));
});

Quick Quiz

Tip

Tip

Practice Array Functions map filter reduce Sort in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Array Functions - map, filter, reduce & Sort

Practice Task

Note

Practice Task - (1) Write a working example of Array Functions map filter reduce Sort from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Array Functions map filter reduce Sort is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done