Skip to Content
Course content

89: array_map, array_filter, array_reduce

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Listen, I've seen this in a dozen pull requests from junior devs: using array_map simply because they want to "loop through an array." They think it's just a modern, shorter version of a foreach loop. It's not.

Stop using array_map as a foreach replacement

The biggest mistake you can make here is using array_map to perform "side effects"—like printing a value to the screen or updating a row in a database. Look at this:

// DON'T DO THIS
array_map(function($user) {
    echo "Sending email to " . $user['email'];
    // Imagine a mail() function call here
}, $users);

Why is this wrong? Because array_map is designed to transform data. It expects to return a new array. When you use it just to trigger an action, you're creating a new array in memory that you immediately throw away. It's inefficient and, more importantly, it confuses anyone reading your code. If you just want to "do something" for every item, stick with foreach. I promise your teammates will thank you.

Transforming data with array_map

Use array_map when you have Array A and you want Array B, where every element has been changed by the same rule. For example, let's say you have a list of product prices in cents, but your UI needs them as formatted dollar strings.

$pricesCents = [1999, 4500, 1200, 899];

$formattedPrices = array_map(function($cents) {
    return '$' . number_format($cents / 100, 2);
}, $pricesCents);

// $formattedPrices is now ['$19.99', '$45.00', '$12.00', '$8.99']

The input and output arrays are the same length. That is the golden rule of mapping.

Cleaning the noise with array_filter

While mapping changes the value of the elements, array_filter changes the number of elements. It's your go-to tool for removing data you don't want. If the callback returns true, the item stays. If false, it's gone.

Let's say you have a list of products, but some are out of stock. You shouldn't be showing those to the customer.

$products = [
    ['name' => 'Mechanical Keyboard', 'stock' => 5],
    ['name' => 'Gaming Mouse', 'stock' => 0],
    ['name' => 'UltraWide Monitor', 'stock' => 2],
    ['name' => 'USB-C Cable', 'stock' => 0],
];

$availableProducts = array_filter($products, function($product) {
    return $product['stock'] > 0;
});

// Now you only have the Keyboard and the Monitor in your list.

One quick tip: array_filter preserves the original keys. If you need the array to be re-indexed from 0, 1, 2... you'll want to wrap the result in array_values().

Condensing a list into a single value with array_reduce

This is the one that usually trips people up. array_reduce doesn't return a list; it returns a single value. Think of it like a snowball rolling down a hill, gathering more snow (data) as it goes.

It takes a "carry" (the accumulator) and the "item" (the current element). You return the updated carry for the next iteration.

$cart = [
    ['name' => 'Book', 'price' => 15],
    ['name' => 'Lamp', 'price' => 30],
    ['name' => 'Pen', 'price' => 5],
];

$totalPrice = array_reduce($cart, function($carry, $item) {
    return $carry + $item['price'];
}, 0); // <--- That 0 is the initial value of $carry

// $totalPrice is now 50

I'll be honest: for a simple sum, a foreach is often more readable. But once you start doing more complex reductions—like grouping data or building a custom lookup table—array_reduce becomes incredibly powerful.




📋 Practical Task

Exercise: Processing an Order Invoice

You are building a checkout summary. You have an array of order items, some of which are "gift" items (price 0) and some of which are "taxable".

Your Goal: Use the three functions learned in this lesson to perform the following sequence:

  1. Filter: Remove all items that have a price of 0 (the gifts).
  2. Map: Apply a 10% tax to the remaining items' prices.
  3. Reduce: Calculate the final grand total of the taxable items.

Starting Data:

$orderItems = [
    ['name' => 'Leather Boots', 'price' => 100],
    ['name' => 'Free Stickers', 'price' => 0],
    ['name' => 'Wool Socks', 'price' => 20],
    ['name' => 'Promo Keychain', 'price' => 0],
    ['name' => 'Winter Hat', 'price' => 30],
];

Print the final grand total to the screen. (Expected result: 165)

Rating
0 0

There are no comments for now.

to be the first to leave a comment.