anon
anon

Reputation:

function inside the declaration of a loop?

take this example:

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

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

Is this true? And is this true even for user-defined functions?

Is that code better than this or it's equal?

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

thanks

Upvotes: 3

Views: 360

Answers (3)

Floern
Floern

Reputation: 33904

foreach uses a copy of the given 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 wont work:

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

Here you have to store the exploded array in a separate variable.

Upvotes: 1

Artefact2
Artefact2

Reputation: 7634

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

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

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

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

Upvotes: 0

shamittomar
shamittomar

Reputation: 46692

The separate code is better because it improves readability and maintaining the code will be easier.

Never stuff statements into each other just to remove some lines and make it look compact. Sure, you will be able to save some bytes, but those bytes will bite you later while maintaining it.

Upvotes: 5

Related Questions