How to use array_map with a multidimensional array in PHP

Summary:

There are 2 ways to use array_map with a multidimensional array. You can take an iterative or recursive approach. The recursive approach is more flexible and usually a better choice. Check out the article for more details.

PHP array_map with a multidimensional array

PHP array_map works with a multidimensional array either iteratively or recursively. The iterative approach is more hardcoded while the recursive approach is more generic and efficient. This article explores both of these approaches.

Introduction

PHP array_map is a higher-order function known for transforming array elements based on the logic of the function it receives. There has already been much discussion on higher-order functions and how to use them. The three most popular higher orders are array_map, array_filter, and array_reduce.

So, if you’re curious about knowing all the caveats involved, you can always jump to the articles that have been linked. This article explores ways to use array_map with multidimensional arrays. Generally, array_map works with linear arrays. Internally, it iterates over the array elements and performs the transformations. So, we need to find a workaround for multidimensional arrays.

PHP array_map – A Quick Review

If you’re already familiar with the basics of the function, feel free to skip this section. This section includes a PHP array_map example using a linear or one-dimensional array. So, this example is going to be pretty straightforward.

<?php
$numbers = [1,2,3,4,5];
 
 
function square($x) {
    return $x**2;
}
 
$transformed = array_map('square',$numbers);
 
print_r($transformed);
 
/*
OUTPUT
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)
*/
 
?>

Pretty good! This example serves as a good starting point. Now, multidimensional arrays are not easy to deal with, as there can be many levels. So, let’s see this challenge right away.

Iterative Approach – PHP array_map multidimensional array

The iterative approach is usually the most heads-on approach. That is because it involves explicit loops. If the dimensions are known upfront, that’s the most convenient way to go about this problem. However, there are performance concerns with increasing loops nesting. But for the sake of seeking solutions, that’s the first shot we give. Eventually, we will move to a better solution, something more generic and custom.

So, here we go with PHP array_map example for a multidimensional array.

<?php
$numbers = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9],
   [10, 11, 12]
];
 
function iterative_func($val) {
    foreach($val as $k=>$v) {
        $val[$k] = $v * 10; //Mapping relation.
    }
    return $val;
}
 
$mapped_numbers = array_map('iterative_func', $numbers);
 
 
print_r($mapped_numbers);
 
/*
[
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90],
    [100, 110, 120]
]
*/
?>

The foreach loop in the ‘iterative_func’ iterates through the array, transforming the values. Ideally, this function is supposed to perform the mapping only. Nonetheless, it works fine here. Next is a three-dimensional array, as you will see we will need more loops to deal with it.

<?php
$numbers = [
    [[1, 2, 3]],
    [[11, 12, 13]],
    [[110, 120, 130]]
];
 
function iterative_func($val) {
    foreach($val as $ov) {
        foreach($ov as $k=>$iv)
        $val[$k] = $iv * 10; //Mapping relation.
    }
    return $val;
}
 
$mapped_numbers = array_map('iterative_func', $numbers);
 
 
print_r($mapped_numbers);
 
/*
[
    [[10, 20, 30]],
    [[110, 120, 130]],
    [[1100, 1200, 1300]],
   
]
*/
?>

Voila! Nothing has changed much from the last example except a dimensional and a loop. While this works fine, that’s neither the most generic way nor too efficient. However, the iterative approach is helpful in handling petty scenarios like these or when you don’t want to dive into complexities.

Recursive Approach –  PHP array_map multidimensional array

The recursive approach offers a more generic solution to the problem at hand. As we have mentioned frequently before, this approach is good for any array dimension and doesn’t need to be hard-coded. So, here’s a generic function that we have created for you. It is a recursive function that performs the mapping in place, using the array_map function.

function array_map_recursive($function, &$array)
{
    foreach($array as &$v)
    {
        if(gettype($v) == 'array')
        {
            array_map_recursive($function, $v);
        }
 
        else
        {
           $v =  $function($v);
 
        }
       
    }
}

This recursive function is also higher-order receiving a function as an argument. Also, it receives the input array by reference. Now, just for demo purposes, we have added redundant dimensions to the array, as shown.

$numbers = [
    [[[1, 2, 3]]],
    [[[11, 12, 13]]],
    [[[110, 120, 130]]]
];

The array_map_recursive function doesn’t care much about the dimensions now, thereby focusing more on the mapping part.

array_map_recursive(function($v) {return $v * 10;}, $numbers);
 
print_r($numbers);
 
/*
[
    [[[10, 20, 30]]],
    [[[110, 120, 130]]],
    [[[1100, 1200, 1300]]]
];
*/

So, the function lays out the mapping relation and the rest of the hard work is done by the recursive function. Another edge of this recursive function is that it lets you focus on the mapping function.

Conclusion

This article explores two approaches of using array_map with a multidimensional array in PHP – iterative & recursive. The iterative approach works fine but it doesn’t generalize well. Contrary to this, the recursive approach is generic and more efficient. Moreover, the article also includes a review of the array_map function at the start to set a solid ground for the rest of the sections.

I hope you’ve learned how to use array_map with a multidimensional array in PHP. If you want to learn more about PHP through intuitive and detailed articles and tutorials, check out FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


Article Categories

Article Tags

© 2022 Confident.Systems