array_map()

Last updated on

The PHP array_map takes an array and, for each element in that array, lets you apply a callback function to transform or manipulate each item however you'd like. You need at least two parameters: the first one is for the function—aka callback—and the second is for the array you are working on.

And if you want to use more than one array, well, array_map can handle that too. 

PHP array_map Syntax

Here’s the basic setup:

array_map(callback, array1, ...) // Additional arrays can be included
  • callback: The function to apply to all elements.
  • array1: The array you want to manipulate.

If you’re using multiple arrays, make sure the function can handle that many arguments. For example, if you have five arrays, your function will need to handle five parameters. Here’s a quick look:

<?php 

function callback($param1, $param2, $param3) {
    // Your code here
}

array_map('callback', $array1, $array2, $array3);

Let’s move forward to see examples.

Transforming Arrays with Custom Functions

Let's start with something simple, like taking an array of numbers and wanting to double each one. array_map makes this a breeze:

$array = [1, 2, 3, 4, 5];

$doubleArray = array_map(function($value) {
    return $value * 2;
}, $array);

// Result: $doubleArray = [2, 4, 6, 8, 10]

This takes each number in $array, doubles it, and returns a new array with the updated values.

Applying Custom Functions with array_map

Moving on from basic math, you can use array_map to perform more complex tasks too. Say we want to square each number:

function square($value) {
    return $value ** 2;
}

$array = [2, 4, 6, 8, 10];

$squaredArray = array_map('square', $array);

// Result: $squaredArray = [4, 16, 36, 64, 100]

The square function does the squaring here, while array_map does the work of applying it across the entire array.

Synchronizing Multiple Arrays

One of the great things about array_map is that it lets you use more than one array at a time. Here's an example where we add corresponding elements in two arrays:

$array1 = [1, 2, 3];
$array2 = [4, 5, 6];

$sumArray = array_map(function($a, $b) {
    return $a + $b;
}, $array1, $array2);

// Result: $sumArray = [5, 7, 9];

In the example above, array_map takes one element from each array and puts all of them together to create a new array containing the sums.

String Handling with array_map

array_map isn't just for numbers—you can use it to operate on strings too. Here's how you might strip out extra spaces from each string in an array:

$array = ['  apple  ', 'banana  ', '  cherry'];

$trimmedArray = array_map('trim', $array);

// Result: $trimmedArray = ['apple', 'banana', 'cherry']

Here, trim removes the spaces, and array_map applies it to each element in the array.

Handling Associative Arrays

You can also use array_map on associative arrays. Suppose we have the following array of students and want to change each student's grade to uppercase:

$students = [
    ['name' => 'John', 'grade' => 'a'],
    ['name' => 'Jane', 'grade' => 'b'],
    ['name' => 'Doe', 'grade' => 'c']
];

$uppercaseGrades = array_map(function($student) {
    $student['grade'] = strtoupper($student['grade']);
    return $student;
}, $students);

// Result: $uppercasedGrades has grades in uppercase

This callback function modifies the grade key for each student without changing their name.

Working with Arrays of Different Lengths

If you use array_map with arrays that are of uneven length, it will stop as soon as it reaches the end of the shortest array. Here's what that looks like:

$array1 = [1, 2, 3];
$array2 = [4, 5];

$resultArray = array_map(function($a, $b) {
    return $a + $b;
}, $array1, $array2);

// Result: $resultArray = [5, 7, 3]

In this case, array_map processes the matching elements; if one of the arrays reaches its end, it continues with the remaining values of the other array.

Using array_map Inside a Class

You may want to consider using array_map with a class for better organization; here’s how that is done:

class Transformer {
    public function doubleValue($value) {
        return $value * 2;
    }
}

$array = [1, 2, 3, 4, 5];
$transformer = new Transformer();

$transformedArray = array_map([$transformer, 'doubleValue'], $array);

// Result: $transformedArray = [2, 4, 6, 8, 10]

Here, the Transformer class has a method to double values. We instantiate the class and then apply array_map with the method to every item in the array.

Wrapping Up

One of the powerful ways to handle arrays in PHP is mapping. It keeps your code clean, saves time, and opens up a world of possibilities—from simple transformations to complex operations across multiple arrays.

As you go through the examples above, you’ll see how useful array_map can be when trying to write efficient PHP.

Frequently Asked Questions (FAQs)

  • What is the array_map function in PHP, and how does it work?

    The array_map function in PHP applies a callback function to each element of one or more arrays. It requires at least two parameters: the callback function and the array you want to manipulate. If you want to work with multiple arrays, you can pass additional arrays to array_map, and it will apply the function to each corresponding element.
  • Can array_map handle multiple arrays at once?

    Yes, array_map can handle multiple arrays. When you pass additional arrays, array_map will process each corresponding element in all arrays. Here’s an example where it adds up values from two arrays:
    $array1 = [1, 2, 3];
    $array2 = [4, 5, 6];
    
    $sumArray = array_map(function($a, $b) {
        return $a + $b;
    }, $array1, $array2);
    
    // Result: $sumArray = [5, 7, 9]
    
  • How can I use a custom function with array_map?

    You can use a custom function with array_map by defining the function first and then passing it as a callback. Here’s an example where we square each number in an array:
    function square($value) {
        return $value ** 2;
    }
    
    $array = [2, 4, 6, 8, 10];
    
    $squaredArray = array_map('square', $array);
    
    // Result: $squaredArray = [4, 16, 36, 64, 100]
    
  • Does array_map work with associative arrays?

    Yes, array_map works with associative arrays. It applies the callback to each element in the array while maintaining the array’s keys. Here’s an example that changes each student’s grade to uppercase:
    $students = [
        ['name' => 'John', 'grade' => 'a'],
        ['name' => 'Jane', 'grade' => 'b'],
        ['name' => 'Doe', 'grade' => 'c']
    ];
    
    $uppercasedGrades = array_map(function($student) {
        $student['grade'] = strtoupper($student['grade']);
        return $student;
    }, $students);
    
    // Result: $uppercasedGrades has grades in uppercase
    
  • What happens if I use array_map with arrays of different lengths?

    When using array_map with arrays of different lengths, it processes elements until the shortest array ends. If one array is shorter, array_map stops processing when it runs out of elements in that array:
    $array1 = [1, 2, 3];
    $array2 = [4, 5];
    
    $resultArray = array_map(function($a, $b) {
        return $a + $b;
    }, $array1, $array2);
    
    // Result: $resultArray = [5, 7, 3]
    
  • Can I use array_map with a class method?

    Yes, you can use array_map with a class method by passing an array that includes an instance of the class and the method name. Here’s how to do it:
    class Transformer {
        public function doubleValue($value) {
            return $value * 2;
        }
    }
    
    $array = [1, 2, 3, 4, 5];
    $transformer = new Transformer();
    
    $transformedArray = array_map([$transformer, 'doubleValue'], $array);
    
    // Result: $transformedArray = [2, 4, 6, 8, 10]
    
  • What’s the difference between array_map and array_walk?

    The main difference is that array_map returns a new array with transformed elements, while array_walk modifies the array directly without returning a new array. Use array_map when you want to create a new array and array_walk when you want to update the array in place.
Share on:

Did you find this tutorial useful?

Your feedback helps us improve our tutorials.