Which is more performative - foreach or array_map?

1

Which of the two are more performative, foreach?

foreach ($example as $val) $ex[] = str_replace(...);

or

$ex = array_map(function ($val) {
    return str_replace(...);
}, $example);

I think it's the foreach, if in what case should I use array_map and why?

Which of the following best practices best practices, or does not fit this scope?

    
asked by anonymous 26.07.2016 / 00:47

1 answer

7

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 .

    
26.07.2016 / 02:35