开发者

PHP foreach(...) question

I was wondering if using

foreach(get_some_array() as $boo) do_something...

is slower than

$arr = get_some_array();
foreach($arr as $boo) do_something...

I mean would get_some_array() be called like 10000000 times if the array would h开发者_运维百科ave so many elements (in the 1st example) ?


No, that function will be called just 1 time. You can verify this by doing:

<?php
function get()
{
    echo "getting\n";

    return array('a', 'b', 'c', 'd');
}

foreach (get() as $v) {
    echo $v . "\n";
}
?>

Here it outputs:

murilo@mac:regionais$ php -f teste.php 
getting
a
b
c
d


$arr = get_some_array(); theoretically adds zero time to this equation, so it really wont make a difference what you use here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜