3

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

shamittomar
  • 46,210
  • 12
  • 74
  • 78

3 Answers3

5

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.

shamittomar
  • 46,210
  • 12
  • 74
  • 78
  • In the wild you see some constructs like `explode()` in `foreach` quite often, so it doesnt disturb the readability very much. I dont see any good reason for the extra expression/variable. Of course that is only useful for common and short expressions within the `foreach` statement. – KingCrunch Feb 18 '11 at 19:02
  • 2
    I disagree. Putting lots of useless variables in the code definitely won't make it easier to understand. There are /some/ cases where this syntax is appropriate. – Artefact2 Feb 18 '11 at 19:06
1

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.

Floern
  • 33,559
  • 24
  • 104
  • 119
0

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.

Artefact2
  • 7,516
  • 3
  • 30
  • 38