PHP array_map Function: How to Transform Arrays with Examples

PHP array_map Function

PHP added the array_map() function to help you apply one function to each item in an array. You do not need to loop manually. The function makes your code short to read.

Understand What array_map Function Is in PHP

The array_map function lets you take a callback and run it on every value in an array. It creates a new array with the changed values. It never changes the original array.

PHP runs the function on each element of the array when you pass just one array. This is useful when you need to change every value without writing a manual loop.

Here is the syntax:

array_map(callback, array1, array2, ...);

The first argument is a callable function. The rest are one or more arrays.

So, what does array_map function return?

The array_map() function returns an array. It never changes the input arrays. Instead, it creates and returns a new array with the results from the callback function.

The function looks at the number of arrays you pass. If you pass more than one, it picks the value at the same index from each array and gives them to the callback.

For example:

$numbers = [1, 2, 3];
$result = array_map('sqrt', $numbers);
print_r($result);

The output:

[1, 1.4142, 1.7320]

You can pass more than one array. The function will use values with the same index from each array as arguments to the callback.

$a = [1, 2, 3];
$b = [10, 20, 30];

$result = array_map(function ($x, $y) {
    return $x + $y;
}, $a, $b);

print-r($result);

Output:

[11, 22, 33]

So, what happens when arrays have different lengths?

PHP stops at the shortest one if the arrays do not have the same number of items. It skips the rest.

$a = [1, 2];
$b = [10, 20, 30];

$result = array_map(function ($x, $y) {
    return $x + $y;
}, $a, $b);
print_r($result);

Output:

[11, 22]

This code adds values from two arrays using the same index. PHP stops at the shorter array.

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. The function has no name and sits right where you need it.

$words = ['one', 'two', 'three'];
$result = array_map(function ($word) {
    return strtoupper($word);
}, $words);
print_r($result);

Here is the output:

['ONE', 'TWO', 'THREE']

You do not need to define the function somewhere else. This helps keep your code focused and easier to read.

Use built-in PHP functions and User-Defined Functions with PHP array_map

You can pass any built-in PHP function that takes one or more arguments. PHP will call that function on each set of values from the input arrays.

$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.

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 using a 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.

This is the difference between array_map and foreach in PHP:

array_map applies a callback function to each value of one or more arrays. It works well when you only need to change the values. However, it does not provide access to the keys inside the callback.

foreach loops through the array and gives you access to both keys and values. This makes it more flexible when you need to work with keys or want to keep keys in the result.

Examples of PHP array_map Function in PHP

Capitalize words in a sentence:

$words = ['hello', 'world'];
$result = array_map('ucfirst', $words);
print($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 $input array stays unchanged.
  • The array_map function 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($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 using an 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_map runs 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 trim or strtoupper.
  • 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 null as the callback, array_map groups 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?

No. It returns a new array and leaves the original one unchanged.

What happens if I pass no arrays to array_map?

It returns an empty array.

Can I use array_map without a callback?

Yes. If you pass null as the callback, array_map will return the arrays combined into a list of arrays by index.
$a = [1, 2];
$b = [3, 4];
$result = array_map(null, $a, $b);
// [[1, 3], [2, 4]]

Is array_map faster than a foreach loop?

Not always. It depends on the logic and array size. But it keeps your code shorter and easier to follow.
Previous Article

PHP trim(): How to remove Whitespace from String

Next Article

PHP mb_strtolower: How to Handle Multibyte Strings Properly

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.