1. Code
  2. PHP

How to Use the array_map Function in PHP With Examples

Scroll to top

In this quick article, we’ll discuss the array_map function in PHP. Basically, we’ll go through the syntax of the array_map function and demonstrate how to use it with real-world examples.

The array_map function allows you to apply a callback function to transform elements of an array. It’s really useful when you want to perform a specific operation on every element of an array. Apart from that, it also allows you to combine multiple arrays into a single multidimensional array.

Instead of iterating through all the array elements with the foreach construct to perform a specific operation on them, you should prefer the array_map function, which is built specifically for this.

Syntax of the array_map Function

In this section, we’ll go through the syntax of the array_map function to understand how it works.

Let’s have a look at the syntax of the array_map function:

1
array_map ( callable|null $callback , array $array , array ...$arrays ) : array

The first argument is the callback function, which is called when the array_map function iterates over the elements of an array. It could be a user-defined function or a class method in the callable form. 

The second argument is the source array on which the callback function will run.

In most cases, you would only need these two arguments. But the array_map function allows you to pass additional array arguments that are passed as arguments to the callback function. They will all be combined into one multi-dimensional array in the output. It’s interesting that you can pass null as the callback, and array_map just performs a zip operation on the source arrays. I'll demonstrate this with a couple of real-world examples in the next section.

The array_map function returns an array of all values processed by the callback function.

In the next section, we’ll go through a couple of real-world examples to understand how the array_map function works.

Real-World Examples

In this section, we’ll discuss how to use the array_map function in different ways.

How to Lowercase an Array

This is one of the most basic and useful examples. When you want to perform a specific operation on all the elements of an array, the array_map function is the way to go!

1
<?php
2
function lowercase($element)
3
{
4
    return strtolower($element);
5
}
6
7
$array = ['Apple', 'BANANA', 'Mango', 'orange', 'GRAPES'];
8
$results = array_map('lowercase', $array);
9
print_r($results);
10
/**

11
Output:

12
Array

13
(

14
    [0] => apple

15
    [1] => banana

16
    [2] => mango

17
    [3] => orange

18
    [4] => grapes

19
)

20
**/
21
?>

As you can see, we’ve passed the lowercase callable in the first argument, so this converts all the elements of an array to lowercase.

How to Use array_map With a Class

In this example, we’ll see how you can apply a class method to all the elements of an array.

1
<?php
2
class Utility
3
{
4
    public function formatPrice($element)
5
    {
6
        if (strpos($element, '$') === FALSE) {
7
                return '$' . $element;
8
        }
9
        return $element;
10
    }
11
}
12
13
$objUtility = new Utility();
14
$array = ['1', '$4', '6', '3', '$10'];
15
$results = array_map(array($objUtility, 'formatPrice'), $array);
16
print_r($results);
17
/**

18
Output:

19
Array

20
(

21
    [0] => $1

22
    [1] => $4

23
    [2] => $6

24
    [3] => $3

25
    [4] => $10

26
)

27
**/
28
?>

In the above example, we’ve passed array($objUtility, 'formatPrice') as a callable in the first argument. Basically, we’re just checking if an array element is prefixed with the $ sign, and if it doesn’t, we’re prepending it.

Zip Operation on Multiple Arrays

Recall that in the syntax of the array_map function, you can pass null as the first argument instead of a callable. In this section, we’ll see how that works with an example.

1
<?php
2
$employeeNames = ['john', 'mark', 'lisa'];
3
$employeeEmails = ['john@example.com', 'mark@example.com', 'lisa@example.com'];
4
$results = array_map(null, $employeeNames, $employeeEmails);
5
print_r($results);
6
/**

7
Output:

8
Array

9
(

10
    [0] => Array

11
        (

12
            [0] => john

13
            [1] => john@example.com

14
        )

15
    [1] => Array

16
        (

17
            [0] => mark

18
            [1] => mark@example.com

19
        )

20
    [2] => Array

21
        (

22
            [0] => lisa

23
            [1] => lisa@example.com

24
        )

25


26
)

27
**/

As we have passed the null value in the first argument, it performs a zip operation on all the arrays that are passed from the second argument onwards. In our case, we’ve passed two arrays, and the array_map function combines them into a single multidimensional array.

Multiple Arguments

As we discussed earlier, you can pass multiple arrays to array_map. In this section, we’ll see how you can use that with a callback function.

1
<?php
2
class Employee
3
{
4
    public $name;
5
    public $employee;
6
7
    public function __construct($name, $employee)
8
    {
9
        $this->name = $name;
10
        $this->employee = $employee;
11
    }
12
}
13
14
function createEmployeeObject($name, $email)
15
{
16
    return new Employee($name, $email);
17
}
18
19
$employeeNames = ['john', 'mark', 'lisa'];
20
$employeeEmails = ['john@example.com', 'mark@example.com', 'lisa@example.com'];
21
$results = array_map('createEmployeeObject', $employeeNames, $employeeEmails);
22
print_r($results);
23
/**

24
Output:

25
Array

26
(

27
    [0] => Employee Object

28
        (

29
            [name] => john

30
            [employee] => john@example.com

31
        )

32


33
    [1] => Employee Object

34
        (

35
            [name] => mark

36
            [employee] => mark@example.com

37
        )

38


39
    [2] => Employee Object

40
        (

41
            [name] => lisa

42
            [employee] => lisa@example.com

43
        )

44


45
)

46
**/

In the above example, the createEmployeeObject callable generates an array of Employee objects.

Conclusion

In this article, we discussed the basics of the array_map function in PHP. We also went through a couple of real-world examples to demonstrate the power of the array_map function.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.