Introduction
I never liked the syntax of array_map but generator support in
php 5.5 makes mapping a little bit more readable and much more
memory-efficient.
With array map
$numbers = [1, 2, 3]; $result = array_map( function($i) { return $i = $i + 1; }, $numbers ); print_r($result);
Array
(
[0] => 2
[1] => 3
[2] => 4
)
Note that the $result array contains the entire mapped result. This is different with generators as you will see in the next block.
With generator
function increaseByOne($numbers) { foreach ($numbers as $number) { yield $number + 1; } } print_r(iterator_to_array( increaseByOne([1, 2, 3]) ));
Array
(
[0] => 2
[1] => 3
[2] => 4
)
The generator function increaseByOne has to be looped to get any
results as it is processes the input array one element at a time. The
array_map function will return the whole mapped array.
With nested array maps
Option 1
$numbers = [1, 2, 3]; $result = array_map( function($j) { return $j * 2; }, array_map( function($i) { return $i = $i + 1; }, $numbers ) ); print_r($result);
Array
(
[0] => 4
[1] => 6
[2] => 8
)
Option 2
function increaseByOne($numbers) { return array_map( function($i) { return $i = $i + 1; }, $numbers ); } function multiplyByTwo($numbers) { return array_map( function($j) { return $j * 2; }, $numbers ); } print_r(multiplyByTwo(increaseByOne([1, 2, 3])));
Array
(
[0] => 4
[1] => 6
[2] => 8
)
With nested generators
function increaseByOne($numbers) { foreach ($numbers as $number) { yield $number + 1; } } function multiplyByTwo($numbers) { foreach ($numbers as $number) { yield $number * 2; } } print_r(iterator_to_array( multiplyByTwo(increaseByOne([1, 2, 3])) ));
Array
(
[0] => 4
[1] => 6
[2] => 8
)