PHP foreach 循环中的数组是如何读取的? [英] How is an array in a PHP foreach loop read?

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

问题描述

我们都听说过在 for 循环中,我们应该这样做:

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
}

而不是这个:

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

出于性能原因(即初始化 $count 只会调用一次 count(),而不是每次都调用 count()条件检查).

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

如果在 foreach 循环中,我这样做是否也会有所不同:

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
}

而不是这个:

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

假设情况允许我使用其中之一?也就是说,PHP 是在两种情况下都只调用一次函数,还是像 for 一样,第二种情况会一次又一次地调用函数?

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()使用迭代器实现 - 因此它只调用一次返回数组的函数,然后使用指向现有结果集的迭代器继续每个项目.

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天全站免登陆