Get your next remote job on LaraJobs.
1 contributor Edit on GitHub PHP

Making sense of PHP's array_map() function

Table of contents:

Making sense of PHP's array_map() function

About array_map()

The array_map() function in PHP is extremely useful to write leaner code when transforming arrays and avoid lengthier loops with temporary variables and an additional indentation level.

When I was inexperienced with PHP, I had a hard time understanding the array_map() function. Now, things have changed, so let me desmystify this super handy function for you!

How to use array_map() in PHP

The array_map() takes a callable as its first parameter, and the array we want to transform as its second parameter. It then returns the a fresh array that has freshly been transformed.

Now, imagine we have an array of prices that we want to apply a discount to.

Before array_map(), we would use a code that looks like this:

function discount($price)
{
return $price * (1 - 0.2);
}
 
$prices = [
10, 20, 30, 40, 50,
];
 
$discounted_prices = [];
 
foreach ($prices as $price)
{
$discounted_prices[] = discount($price);
}

This is good, but we can do better thanks to array_map():

function discount($price)
{
return $price * (1 - 0.2);
}
 
$prices = [
10, 20, 30, 40, 50,
];
 
$discounted_prices = array_map(discount(...), $prices);

$discounted_prices now contains:

[
8,
16,
24,
32,
40,
];

Also, did you know that array_map() can also accept a closure (or anonymous function)?

$prices = [
10, 20, 30, 40, 50,
];
 
$discounted_prices = array_map(function ($price) {
return $price * (1 - 0.2);
}, $prices);

But wait, did you really think this is it? Why not use the arrow syntax on our closure?

$prices = [
10, 20, 30, 40, 50,
];
 
$discounted_prices = array_map(
fn ($price) => $price * (1 - 0.2),
$prices
);

There you have it! Using array_map() can drastically help improving your code. Now, you can take a look at other similar functions such as array_filter() or array_reduce().

One more thing about array_map()

Ha! You thought that was really it, right? No! array_map() is such a useful function to use in PHP!

So, what you probably didn’t know is that it can accept an infinite amount of arrays to loop through. Here’s an example:

$products = [
'Apple Watch',
'iMac',
'iPhone',
'Mac Studio',
'MacBook Pro',
];
 
$prices = [
10, 20, 30, 40, 50,
];
 
$discounted_products = array_map(function ($product, $price) {
return [
'product' => $product,
'discounted_price' => $price * (1 - 0.2)
];
}, $products, $prices);

In this block of code, we build a unique multidimensional array out of two dinstinct ones and apply the discount.

[
[
'product' => 'Apple Watch',
'discounted_price' => 8,
],
]
Benjamin Crozat

Written by Benjamin Crozat

Indie hacker, blogger, and AI enthusiast building things with the TALL stack. 🔥

Follow me on:

Recommended articles

Learn how to sort any kind of array in PHP Learn how to sort any kind of array in PHP

Let me walk you through some of the most useful functions in PHP that will enable you to sort any kind of array.

Published on Nov 9, 2023

PHP
Understanding array_filter() in PHP Understanding array_filter() in PHP

See how PHP allows you to filter unwanted values in arrays in a simple and concise way.

Published on Nov 11, 2023

PHP
20+ Laravel best practices, tips and tricks to use in 2023 20+ Laravel best practices, tips and tricks to use in 2023

Learning a framework can be overwhelming, but time and execution will make you a master. Here are some best practices to help you toward your goal.

Modified on Oct 17, 2023

PHP 8.3 is out, now! Here's what's new and changed. PHP 8.3 is out, now! Here's what's new and changed.

PHP 8.3 was released on November 23, 2023, and as usual, you need to be up to date with new features and breaking changes for easier transitions.

Modified on Nov 23, 2023

PHP
Laravel interview questions and answers for 2023 Laravel interview questions and answers for 2023

Nailing a Laravel job interview can be a daunting task, but with the right preparation and mindset, you can set yourself up for success.

Modified on Sep 19, 2023 Audio available

14 Laravel Collections tips to refactor your codebase 14 Laravel Collections tips to refactor your codebase

Laravel Collections make arrays more powerful and convenient to work with. This article provides tons of quick tips to instantly make your codebase better.

Modified on Aug 27, 2023

Gold sponsors New

  • Wire Elements
    Beautiful handcrafted Livewire components.
    Check site
Your business here

Partners

If you buy from one of my partners below, I will be compensated at no cost to you. These are services I use or used, and 100% stand behind.

  • Scalable and reliable VPS hosting.
    Bonus: $200 of free credits
    Check site
  • The Google Analytics alternative without compromise.
    Free trial: 30 days
    Bonus: $10 off your first invoice
    Check site
  • Flare
    Track PHP and JavaScript errors in one place.
    Free trial: 10 days
    Check site
  • Keep track of your Google rankings.
    Free trial: 7 days
    Promo code: WELCOME30
    Check site
- / -