Has the launch exploded more than once in foreach?

$array='hello hello2'; foreach(explode(' ',$array) as $v) echo $v; 

How many times does it explode?

And is it better to use another var:

  $exploded = explode(...); foreach($exploded as $v) ... 

?

+6
source share
5 answers

It starts only once. foreach will work with a copy of the explode return value (array or false).

foreach is a language construct that expects $array as $key => $value . $array can be any expression that evaluates an array, and explode is such a function. An expression is evaluated only once, and then foreach works with the result of the expression.

This is different from a regular for loop, for example. The for loop accepts three expressions. Both the second and third expressions are evaluated for each iteration of the loop.

Thus, there may be a difference with the for loop (leaving optimization and the O (1) action count aside) between these two statements:

 for($i = 0; $i < count($array); ++$i) { … } // vs. for($i = 0, $c = count($array); $i < $c; ++$i) { … } 
+8
source

explode will only be called once and will provide the returned foreach array for iteration.

If it is called only once with foreach , you may not want to go with another variable.

But if your explosion fails and returns false anyway, foreach will issue a warning, so the presence of another variable will give you more control over these warnings and error handling.

+1
source

It starts only once. foreach Documents will work with a copy of the returned value explode Documents .

Since the expression containing explode will be evaluated once (it is not inside the loop), explode will be executed only once.

But since the return value can be array or FALSE , and foreach only works with types array or Object , this will not work for FALSE , which should make it necessary to first check the result before executing foreach which needs a variable if you want to execute explode only once:

 $array='hello hello2'; if (FALSE === $exploded = explode(' ',$array)) { throw new RuntimeException('Explode failed.'); } foreach ($exploded as $v) { echo $v; } 

In this example, for the foreach part, $exploded is evaluated only once.

See also: Traversable .

+1
source

Runs only once explode , feel free to use the first.

0
source

the second will make your code more readable and give you the ability to display the final contents of the array for debugging purposes.

-4
source

Source: https://habr.com/ru/post/901939/


All Articles