0
0
PHPprogramming~3 mins

Why Array map function in PHP? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could change every item in a list with just one simple command instead of repeating yourself?

The Scenario

Imagine you have a list of prices and you want to add tax to each price manually by writing code for each item.

The Problem

Doing this manually means repeating code for every item, which is slow and easy to make mistakes. If the list grows, your code becomes messy and hard to fix.

The Solution

The array map function lets you apply the same change to every item in the list with just one simple command, making your code clean and error-free.

Before vs After
Before
$prices = [10, 20, 30];
$prices_with_tax = [];
$prices_with_tax[] = $prices[0] * 1.1;
$prices_with_tax[] = $prices[1] * 1.1;
$prices_with_tax[] = $prices[2] * 1.1;
After
$prices = [10, 20, 30];
$prices_with_tax = array_map(fn($price) => $price * 1.1, $prices);
What It Enables

You can quickly transform every item in a list with one clear, simple command.

Real Life Example

Updating a list of product prices to include tax or discounts without rewriting code for each product.

Key Takeaways

Manual changes to each item are slow and error-prone.

Array map applies a function to every item automatically.

This makes code shorter, cleaner, and easier to maintain.