The problem is sometimes confusing the purpose of each thing.
array_map
has numerous features, which go beyond those presented in the question examples.
array_map
is intended to map a array
based on a function passed by callback
.
Example:
array_map('trim', [' wallace ', ' bacco ', ' guilherme ']);
Result:
['wallace', 'bacco', 'guilherme']
Notice that the trim
function has been called for every array
item.
In this case, if I compare with foreach
, I would think of practicality (and not just performance), because if I were to do with foreach
, this code would look like this:
$arr = [' wallace ', ' bacco ', ' guilherme '];
foreach ($arr as &$value) $value = trim($value);
So you have to keep in mind that the purpose / purpose of each is different.
Another example for you to understand this is: Ever wondered why in array_map
the callback is passed as argument first than array
? It is because array_map
allows multiple arrays
- something that would make a lot of foreach
.
See:
array_map(function ($v1, $v2, $v3) {
echo $v1, $v2, $v3;
}, ['a', 'b', 'c'], [1, 2, 3], ['@', '!', '&']);
The result would be:
'a1@'
'b1!'
'c3&'
That is, with array_map
you have the possibility to map one or more array
, and not only map one.
NOTE : In the example above, I used echo
within the array_map
callback, but it is not very useful to do with array_map
.
In the end, I've done these examples with array_map
only to understand that there is no need to compare foreach
to array_map
, since they have different purposes.
You could, for example, want to compare array_map
with array_walk
, but if you see the purpose of each, you will see that they do not do the same thing.
So my conclusion is: Use array_map
to map, and foreach
, to traverse array
.