$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)
...
?
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) { … }
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.
It only gets executed once. foreach
Docs will operate on a copy of the return value of explode
Docs.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With