PHP added the array_map() function to help you apply one function to each item in an array.
Table of Content
Understand the array_map Function in PHP
The array_map() function runs a callback on each element of one or more arrays. It returns a new array and never changes the originals. This lets you change every value without a loop.
Here is the syntax:
array_map(callback, array1, array2, ...);The first argument is a function or a callable that runs on each element when you pass an array. It takes elements from the same index as arguments when you pass multiple arrays.
The Shorter arrays are padded with empty values when the lengths are different, and the iteration continues until the longest array is finished.
For a quick example:
$a = [1, 2, 3];
$b = [4, 5, 6];
$result = array_map(function($x, $y) {
return $x * $y;
}, $a, $b);
print_r($result);The output:
Array
(
[0] => 4
[1] => 10
[2] => 18
)
The callback takes two variables, which are $x and $y. So each one is from the same index in the arrays to multiply their values together.
So, what happens if the arrays have different lengths in array_map?
The array_map function follows the longest array and fills shorter arrays with empty values until it finishes the longest one.

Here is an example:
$a = [1, 2, 3, 4, 5];
$b = [10, 20];
$c = [100, 200, 300];
// array_map with a callback
$result = array_map(function($x, $y, $z){
return $x + $y + $z;
}, $a, $b, $c);
print_r($result);The output:
Array
(
[0] => 111
[1] => 222
[2] => 303
[3] => 4
[4] => 5
)
The callback iterates until it reaches the end of the longest array. It fills the shorter arrays with empty values, so in this case, $b has 3 empty values and $c has 2.
Here is an image that shows you what happens exactly:

Let’s see another example with a built-in function in PHP:
$numbers = [1, 2, 3];
$result = array_map('sqrt', $numbers);
print_r($result);The output:
Array
(
[0] => 1
[1] => 1.4142135623731
[2] => 1.7320508075689
)
This runs sqrt on each number and returns its square roots.
Anonymous Functions within array_map in PHP
You can use an anonymous function as the callback. This gives you more control over how you process each item. This is written directly where it is used.
Here is an example:
$words = ['one', 'two', 'three'];
$result = array_map(function ($word) {
return strtoupper($word);
}, $words);
print_r($result);Here is the output:
['ONE', 'TWO', 'THREE']
It runs the anonymous function on each element and changes the text to uppercase.
Use Built-in PHP Functions and User-Defined Functions with PHP array_map
You can use any built-in PHP function, and PHP will run it on each set of values from the arrays.
For example:
$items = [' apple ', 'banana ', ' pear'];
$result = array_map('trim', $items);
print_r($result);Output:
['apple', 'banana', 'pear']
This works with functions like strlen and strtoupper.
If you want to reuse logic or add complex steps, define your own function and pass it to array_map as a string.
Here is an example:
function double($x) {
return $x * 2;
}
$values = [1, 2, 3];
$result = array_map('double', $values);
print_r($result);Output:
[2, 4, 6]
This code doubles each value in the array with the user-defined function.
You can also mix in multiple arrays:
function multiply($x, $y) {
return $x * $y;
}
$a = [2, 4, 6];
$b = [3, 5, 7];
$result = array_map('multiply', $a, $b);
print_r($result);Result:
[6, 20, 42]
This code uses a user-defined function to multiply values from two arrays by their index.
The Difference Between array_map and foreach
The foreach is a loop that goes through each element of an array. It can read, change, or remove values directly in the original array.
But the array_map applies a callback function to each value of one or more arrays. It doesn’t affect the original array.
Here is a table that shows you the key differences between each one:
| Feature | array_map | foreach |
|---|---|---|
| Return value | Returns a new array | Does not return anything |
| Original array | Stays unchanged | Can be changed inside the loop |
| Callback use | Needs a function (named or anonymous) | No function needed, just loop logic |
| Multiple arrays | Can work on more than one array at the same time | Works on one array at a time |
| Style | Functional programming style | Procedural/imperative style |
So, you can use array_map if you don’t need to touch the main array and want to create a new array with updates. Use foreach if you need to change the original array.
Examples of PHP array_map Function in PHP
Capitalize words in a sentence:
$words = ['hello', 'world'];
$result = array_map('ucfirst', $words);
print_r($result);Output:
['Hello', 'World']
This code applies the ucfirst function to each word. That makes the first letter uppercase.
Use array_map to return an array:
$input = [1, 2, 3, 4];
$output = array_map(function ($n) {
return $n * 10;
}, $input);
print_r($output);The output:
[10, 20, 30, 40]
In this example:
- The function multiplies each number by 10.
- The original
$inputarray stays unchanged. - The
array_mapfunction returns a new array with the changed values.
Format numbers as strings:
$nums = [1000, 2000, 3000];
$result = array_map(function ($n) {
return number_format($n);
}, $nums);
print_r($result);Output:
['1,000', '2,000', '3,000']
This code uses an anonymous function to format each number with commas.
Combine two arrays of first and last names:
$first = ['John', 'Jane'];
$last = ['Doe', 'Smith'];
$result = array_map(function ($f, $l) {
return "$f $l";
}, $first, $last);
print_r($result);Output:
['John Doe', 'Jane Smith']
This code combines first and last names within the anonymous function with two arrays.
Associative arrays and the limitation of array_map:
$data = [
'a' => 1,
'b' => 2,
'c' => 3,
];
$result = array_map(function($value) {
return $value * 2;
}, $data);
print_r($result);The output:
[2, 4, 6]
The callback gets only the values (1, 2, 3). The keys (‘a’, ‘b’, ‘c’) are lost in the result.
Challenges of array_map() Function
Challenge 1: Apply Multiple Rules to Combine Data
You have product data:
$ids = [101, 102, 103];
$names = ['Widget', 'Gadget', 'Thing'];
$stock = [0, 5, 2];Use array_map() to return an array of messages:
- If stock = 0, return
"Product Widget (ID: 101) is out of stock." - Otherwise, return
"Product Widget (ID: 101) has 5 units available."
Expected output:
Array
(
[0] => Product Widget (ID: 101) is out of stock.
[1] => Product Gadget (ID: 102) has 5 units available.
[2] => Product Thing (ID: 103) has 2 units available.
)
Your answer:
Challenge 2: Combine and Transform
You have three arrays:
$prices = [10, 20, 30];
$quantities = [2, 4, 6];
$discounts = [0.1, 0.2, 0.15];Use array_map() to calculate the final amount for each product with this formula:
(price × quantity) × (1 - discount)
Expected output:
Array
(
[0] => 18
[1] => 64
[2] => 153
)
Your answer:
Challenge 3: Find Maximum per Row
You have:
$a = [3, 8, 1];
$b = [5, 2, 9];
$c = [4, 7, 6];Use array_map() to build an array containing the maximum value from each index across all three arrays.
Expected output:
[5, 8, 9]
Your answer:
Wrapping Up
You learned what the array_map function does and how it works with one or more arrays. You also saw how to use it with anonymous functions and built-in functions.
Here is a quick recap to help you remember:
array_mapruns a function on each item in one or more arrays.- It returns a new array and keeps the original one unchanged.
- You can use it with built-in PHP functions like
trimorstrtoupper. - It works with input arrays of the same or different lengths.
- You can also pass anonymous or user-defined functions.
- If arrays have different lengths, PHP stops at the shortest one.
- It uses the same index to group values from multiple arrays. This is how it forms sets like the array 0 array pair.
- When you pass
nullas the callback,array_mapgroups values by index. - It helps you avoid loops when you want to change all elements of an array.
FAQs
Can array_map change the original array?
What happens if I pass no arrays to array_map?
Can I use array_map without a callback?
$a = [1, 2];
$b = [3, 4];
$result = array_map(null, $a, $b);
// [[1, 3], [2, 4]]
Is array_map faster than a foreach loop?
Similar Reads
The array_intersect_ukey is used to compare arrays by keys with a custom function in PHP. It returns matches by keys…
You need the array_is_list function to know if an array works as a list or not in PHP. What is…
Deleting records in MongoDB is a common task. You might need to clear old data, remove outdated entries, or handle…
This guide shows how PHP array_keys finds all keys in an array and how you can filter them by a…
There are some tools known as "PHP magic constants" that will make your code a little more clever and versatile.…
PHP array_diff_uassoc compares arrays by values and keys. You can also pass a custom function to compare keys in your…
In this tutorials, we are going to explain the PHP MySQL Delete Data process with a simple, unique guide. By…
Variables in PHP are general elements used for data storage and other manipulations. Global variables belong to a particular category…
If you are working with PHP and MySQL, one of the first tasks you may need is to create a…
The PHP array_key_exists function checks a given key in an array and tells if that key exists or not. Understand…