在一个PHP foreach循环数组是怎么看? [英] How is an array in a PHP foreach loop read?

查看:158
本文介绍了在一个PHP foreach循环数组是怎么看?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都听说了如何在循环,我们应该这样做:

 为($ i = 0,$计数=计数($数组); $ I< $ C ++ $ I)
{
    //做的东西在遍历数组
}

而不是这样的:

 为($ I = 0; $ I<计数($数组); $ + I)
{
    //做的东西在遍历数组
}

由于性能原因(即初始化 $计数会一直叫计数()只有一次的,而不是调用计数()与每一个条件检查)。

难道那么它也有所作为,如果在一个的foreach 循环,我这样做:

  $阵列= do_something_that_returns_an_array();的foreach($数组$关键=> $ VAL)
{
    //做的东西在遍历数组
}

而不是这样的:

 的foreach(do_something_that_returns_an_array()为$关键=> $ VAL)
{
    //做的东西在遍历数组
}

假设的情况下让我要么使用?也就是说,是否PHP在两种情况下调用该函数只有一次,或者是像,其中第二种情况会一次又一次地调用该函数?


解决方案

的foreach()是的implemented使用迭代 - 因而它仅调用一次返回的数组的函数,然后使用它指向设置继续与每个项目的现有结果迭代

We have all heard of how in a for loop, we should do this:

for ($i = 0, $count = count($array); $i < $c; ++$i)
{
    // Do stuff while traversing array
}

instead of this:

for ($i = 0; $i < count($array); ++$i)
{
    // Do stuff while traversing array
}

for performance reasons (i.e. initializing $count would've called count() only once, instead of calling count() with every conditional check).

Does it then also make a difference if, in a foreach loop, I do this:

$array = do_something_that_returns_an_array();

foreach ($array as $key => $val)
{
    // Do stuff while traversing array
}

instead of this:

foreach (do_something_that_returns_an_array() as $key => $val)
{
    // Do stuff while traversing array
}

assuming circumstances allow me to use either? That is, does PHP call the function only once in both cases, or is it like for where the second case would call the function again and again?

解决方案

foreach() is implemented using iterators - thus it only calls the function that returns an array once, and then uses the iterator which points to the existing result set to continue with each item.

这篇关于在一个PHP foreach循环数组是怎么看?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆