array_map notes

Let's asume we are used to the for loop or maybe foreach, it's the first thing that comes to mind when we have to iterate. It's basic, fast, but not as easy to read or nest with other functions as the array_map, array_filter or array_reduce functions. If we want to get used to those higher-order functions we need to understand them. That's my situation here, and these are the study notes to learn it. Let's start with the array_map

function sum($inFirstArray, $inSecondArray) {
  return $inFirstArray + $inSecondArray;
$firstArray = [1, 2, 3, 4];
$secondArray = [4, 3, 2, 1];
$array = array_map("sum", $inFirstArray, $inSecondArray); // contains (5, 5, 5, 5)

A map (not only in PHP) links one value to another. The array_map takes every element of the array, transforms it according to its provided function, and returns a new array. So it's immutable; we are not changing the original elements but creating new ones.
And we don't have to think of only one array. We could pass many and perform operations between them. We could imagine a matrix where we iterate over every row. There are many use cases: switch arrays of words with their translations, perform math operations... a cool use is when you don't pass any callback, so the first parameter is null. This will create a new associative array of arrays.

$a = [1, 2, 3];
$b = ['one', 'two', 'three'];
$c = ['uno', 'dos', 'tres'];

$d = array_map(null, $a, $b, $c);

    [0] => Array
            [0] => 1
            [1] => one
            [2] => uno

    [1] => Array
            [0] => 2
            [1] => two
            [2] => dos

    [2] => Array
            [0] => 3
            [1] => three
            [2] => tres

The number of parameters that the callback function accepts should match the number of arrays passed to array_map If we send more, it will ignore the excess, and fewer arguments will throw an error.

And that's it. Every time the same operation applies to all elements of an array, we can use a map. Is the for loop more performant? Yeah, but for now, I don't care; my use cases deal with pretty small arrays to see a real difference.

In the next note, we reduce the array to a number. Stay tuned. :)

  • array_map notes
  • Carmen Maymó