Making sense of PHP's array_map() function

Making sense of PHP's array_map() function

Published
Nov 4, 2023
Written by
Benjamin Crozat
0
comments
2 minutes
read

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,
	],
	…
]
About Benjamin Crozat
Benjamin Crozat

Hi! I’m from the South of France and I’ve been a self-taught web developer since 2006. When I started learning PHP and JavaScript, PHP 4 was still widely used, Internet Explorer 6 ruled the world, and we used DHTML to add falling snow on websites.

Being able to educate myself for free on the web changed my life for the better. Giving back to the community was a natural direction in my career and I truly enjoy it.

Therefore, I decided to take action:

  1. I launched this blog in September 2022 with the goal to be in everyone’s Google search. I get more than tens of thousands of monthly clicks from it and even more visits overall (my analytics dashboard is public by the way).
  2. I also started growing my X (formerly Twitter) account at the same time, which has now over 7,000 followers.
  3. All the content I write is free thanks to my sponsors.

I also want to be completely free with my time and make a living with my own products. In April 2024, I launched Nobinge, a tool to summarize and chat with your content, including YouTube videos.

Believe me, I’m just getting started!

0 comments

You need to be signed in to comment this post.
Sign in with GitHub