Which is more performatic - foreach or array_map?

Asked

Viewed 822 times

1

Which of both are more performative, foreach?

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

or

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

I believe it is the foreach, if in which case I should use the array_map and why?

Which of both follows best programming practices, or does not fit this scope?

  • 3

    Do you know the differences between the two? do you know the reason to use array_map to map an array? (I ask that we may respond in a manner adapted to your current knowledge)

1 answer

8


The problem is sometimes to confuse the purpose of each thing.

array_map has numerous functionalities, which go beyond those presented in the examples of the question.

array_map is intended to map a array based on a function passed by callback.

Example:

  array_map('trim', [' wallace ', ' bacco ', ' guilherme ']);

Upshot:

  ['wallace', 'bacco', 'guilherme']

Note that the function trim was called for each item of the array.

In that case, if you compare it to foreach, would think about practicality (and not just performance), because if it were to do with foreach, that 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: Have you ever wondered why on array_map the callback is passed as argument first that the array? That’s because array_map allows for multiple arrays - something that would differentiate much of the foreach.

Behold:

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 just map one.

NOTE: In the above example, I used echo inside the callback of array_map, but it’s not something that’s very useful to do with array_map.

At the end of the day, I made these examples with array_map just to understand that there is no need to compare foreach with array_map, since they have different purpose.

You might, 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 walk the array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.