Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does explode get executed more than once in a foreach? [closed]

Tags:

php

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

How many times does explode get executed?

And is it better that to use another var like:

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

?

like image 554
dynamic Avatar asked Nov 20 '11 11:11

dynamic


3 Answers

It only gets executed once. foreach will operate on a copy of the return value of explode (array or false).

foreach is a language construct which expects $array as $key => $value. $array can be any expression which evaluates to an array, and explode is such a function. The expression is evaluated only once, and then foreach operates on the result of the expression.

This is different with a regular for loop for instance. A for loop takes three expressions. Both the second and third expression are evaluated for each iteration of the loop.

So with a for loop there could be a difference (leaving optimization and the O(1)-performance of count aside) between these two statements:

for($i = 0; $i < count($array); ++$i) { … }
// vs.
for($i = 0, $c = count($array); $i < $c; ++$i) { … }
like image 168
knittl Avatar answered Oct 21 '22 08:10

knittl


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

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

But if your explode failed and returns false in any case, foreach will produce a warning so having in another variable give you more control over those warnings and error handling.

like image 1
Shakti Singh Avatar answered Oct 21 '22 08:10

Shakti Singh


It only gets executed once. foreachDocs will operate on a copy of the return value of explodeDocs.

As the expression containing explode will be evaluated once (it's not inside the loop), explode will only run once.

But as the return value can be an array or FALSE and foreach does operate only on types that are Array or Object, it won't work for FALSE which should make it necessary to check the result first before executing the foreach which needs the 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;
}

With this example, for the foreach part, $exploded is only evaluated once as well.

See as well: Traversable.

like image 1
hakre Avatar answered Oct 21 '22 08:10

hakre