开发者

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 tr开发者_高级运维ue? 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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜