Skip to content

PHP By Exalogics

A Simple Easy Site to Learn, Understand and create php

Menu
  • Home
  • Welcome to php by Exalogics
    • Introduction to PHP
    • How to Install PHP on Windows
    • PHP Variables
    • PHP Constants
    • PHP Switch Statement
    • PHP Data Types
    • PHP Operators
    • PHP If Else Statements
    • PHP E-Commerce Development
    • Your First PHP Script
    • PHP Error Handling
    • PHP Frameworks Guide
    • PHP MySQL Database Development
    • PHP Security Best Practices
    • PHP CMS Development
    • PHP Hosting Guide
  • PHP API Development
Menu

How to Use array_map(), array_filter(), and array_reduce() in PHP

Posted on October 25, 2026






How to Use array_map(), array_filter(), and array_reduce() in PHP – Complete Guide


How to Use array_map(), array_filter(), and array_reduce() in PHP

If you work with PHP on a daily basis, you’ve probably encountered the three core array functions that can transform, filter, and aggregate data with minimal code: array_map(), array_filter(), and array_reduce(). This guide walks you through each function, explains the syntax, provides real‑world examples, and shares best‑practice tips to keep your code clean and performant.

Why These Functions Matter for SEO‑Friendly Code

Search engines love fast, maintainable, and well‑structured code. By using array_map(), array_filter(), and array_reduce() you reduce the number of loops, avoid temporary variables, and make your intent explicit. The result is a smaller page‑load time and a clearer codebase—both of which positively affect SEO rankings.

Understanding array_map()

Syntax

array_map(callable $callback, array $array, array ...$arrays): array

What It Does

array_map() applies a callback function to each element of one or more arrays, returning a new array with the transformed values. It’s the functional‑programming equivalent of a foreach loop that builds a new collection.

Basic Example

<?php
$numbers = [1, 2, 3, 4];
$squared = array_map(function ($n) {
    return $n * $n;
}, $numbers);

print_r($squared);
// Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )
?>

Mapping Multiple Arrays

When you pass more than one array, the callback receives the corresponding elements from each array.

<?php
$a = [1, 2, 3];
$b = [4, 5, 6];
$sum = array_map(fn($x, $y) => $x + $y, $a, $b);
print_r($sum); // Array ( [0] => 5 [1] => 7 [2] => 9 )
?>

Understanding array_filter()

Syntax

array_filter(array $array, ?callable $callback = null, int $mode = 0): array

What It Does

array_filter() removes elements from an array that do not satisfy a given condition. If no callback is supplied, it simply removes all entries that are equivalent to false (e.g., 0, "", null).

Filtering with a Callback

<?php
$users = [
    ['name' => 'Alice', 'active' => true],
    ['name' => 'Bob',   'active' => false],
    ['name' => 'Cara',  'active' => true],
];

$activeUsers = array_filter($users, fn($u) => $u['active']);
print_r($activeUsers);
?>

Preserving Keys

Use the $mode flag ARRAY_FILTER_USE_KEY to filter based on keys instead of values.

<?php
$items = ['a' => 1, 'b' => 2, 'c' => 3];
$evenKeys = array_filter($items, fn($k) => $k !== 'b', ARRAY_FILTER_USE_KEY);
print_r($evenKeys); // Array ( [a] => 1 [c] => 3 )
?>

Understanding array_reduce()

Syntax

array_reduce(array $array, callable $callback, mixed $initial = null): mixed

What It Does

array_reduce() iteratively reduces an array to a single value using a callback that receives an accumulator and the current item. It’s perfect for summations, concatenations, or building complex structures from a list.

Summing Numbers

<?php
$values = [5, 10, 15];
$total = array_reduce($values, fn($carry, $item) => $carry + $item, 0);
echo $total; // 30
?>

Creating a CSV String

<?php
$words = ['apple', 'banana', 'cherry'];
$csv = array_reduce($words, fn($carry, $item) => $carry . ($carry ? ',' : '') . $item, '');
echo $csv; // apple,banana,cherry
?>

Combining the Three Functions

Often you’ll need to transform, filter, and then aggregate data. Below is a practical example that extracts the ages of active users, filters out ages below 18, and calculates the average age.

<?php
$users = [
    ['name' => 'Alice', 'age' => 22, 'active' => true],
    ['name' => 'Bob',   'age' => 17, 'active' => true],
    ['name' => 'Cara',  'age' => 30, 'active' => false],
    ['name' => 'Dave',  'age' => 25, 'active' => true],
];

// 1️⃣ Map: get ages of active users
$activeAges = array_map(
    fn($u) => $u['age'],
    array_filter($users, fn($u) => $u['active'])
);

// 2️⃣ Filter: keep only ages >= 18
$adultAges = array_filter($activeAges, fn($age) => $age >= 18);

// 3️⃣ Reduce: calculate average
$average = array_reduce(
    $adultAges,
    fn($carry, $age) => ['sum' => $carry['sum'] + $age, 'count' => $carry['count'] + 1],
    ['sum' => 0, 'count' => 0]
);
$averageAge = $average['count'] ? $average['sum'] / $average['count'] : 0;

echo "Average adult age of active users: {$averageAge}";
?>

Performance Tips & Best Practices

  • Prefer native callbacks over anonymous functions when possible. Built‑in functions like strlen or intval are faster than custom closures.
  • Keep the callback pure. Avoid side effects (e.g., database writes) inside array_map() or array_filter()—it makes debugging harder and can degrade performance.
  • Use array_reduce() sparingly for very large arrays. A simple for loop may be more memory‑efficient if you need early exit.
  • Leverage type declarations. In PHP 8+, declare return types for callbacks to catch mistakes early.
  • Profile with microtime() or Xdebug. Measure the actual impact before optimizing.

Conclusion

Mastering array_map(), array_filter(), and array_reduce() empowers you to write concise, readable, and high‑performance PHP code. By applying these functions thoughtfully, you not only improve developer productivity but also contribute to faster page loads—an essential factor for SEO success.

Ready to refactor your legacy loops? Start with a single array transformation, test the output, and gradually replace repetitive foreach blocks with these functional tools.



Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How to Use array_map(), array_filter(), and array_reduce() in PHP
  • What Does array_pluck() Do and Why is it Needed?
  • Pakistan Tours and Travels: A Guide to Choosing the Right Agency
  • PHP Array Functions: The Ultimate Cheat Sheet
  • Pakistan Tour Africa: Exploring Cricketing Ties with the Continent

Recent Comments

  1. What are Magic Methods in PHP? (__construct, __destruct, __get, etc.) - 93 Travellers Pakistan on What are Magic Methods in PHP? (__construct, __destruct, __get, etc.)
  2. How to Use Traits in PHP - 93 Travellers Pakistan on How to Use Traits in PHP
  3. What is Polymorphism in PHP? - 93 Travellers Pakistan on What is Polymorphism in PHP?
  4. What is Inheritance in PHP? - 93 Travellers Pakistan on What is Inheritance in PHP?
  5. What is Abstraction in PHP? - 93 Travellers Pakistan on What is Abstraction in PHP?

Archives

  • October 2026
  • September 2026
  • August 2026
  • July 2026

Categories

  • PHP Basics
  • Uncategorized
©2026 PHP By Exalogics | Design: Newspaperly WordPress Theme
imunify-bot-check