Function inside loop declaration?

take this example:

foreach(explode(' ','word1 word2 word3') as $v)
 echo $v;

From what I know, php doens't executes every time the explode function, but will only be executed for the first time.

It's true? And is this true even for custom functions?

Is this code better than this or equal?

$genericVar = explode(' ','word1 word2 word3');
foreach($genericVar as $v)
 echo $v;

thank

+3
source share
3 answers

When using foreach, two pieces of code are equivalent. The explode function will be called only once.

However, this is not how it works for loops, for example:

for($i = 0; $i < count($array); ++$i) {}

In this example, the count function will be called at each iteration.

0
source

Separate code is better because it improves readability and code support will be easier.

, . , , , .

+5

foreach uses a copy of this array, so the function will be executed only once.

foreach(explodecount(' ','A B C') as $v)
   echo $v;

function explodecount($a,$b){
    echo '@';
    return explode($a,$b);
}

// output: @ABC
// not @A@B@C

but this does not work:

foreach(explode(' ','A B C') as &$v)
   echo $v;

Here you must save the exploded array in a separate variable.

+1
source

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


All Articles