PHP foreach 循环中的数组是如何读取的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1685689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:30:37  来源:igfitidea点击:

How is an array in a PHP foreach loop read?

phparraysperformanceloopsforeach

提问by BoltClock

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

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

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 $countwould've called count()only once, instead of calling count()with every conditional check).

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

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

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

$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 forwhere the second case would call the function again and again?

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

回答by Amber

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.

foreach()使用迭代器实现的-因而仅调用函数返回一个数组一次,然后使用迭代点到现有的结果集继续与每一个项目,其。

回答by NawaMan

I think testing it will surely answer that.

我认为测试它肯定会回答这个问题。

Here is my code:

这是我的代码:

function GetArray() {
    echo "I am called.\n";
    return array("One"=>1, "Two"=>2, "Three"=>3, "Four"=>4, "Five"=>5);
}

echo "Case #1\n";
$array = GetArray();
foreach ($array as $key => $val){
    // Do stuff while traversing array
    echo "    Inside the loop: $key => $val\n";
}
echo "\n";

echo "Case #2\n";
foreach (GetArray() as $key => $val) {
    // Do stuff while traversing array
    echo "    Inside the loop: $key => $val\n";
}
echo "\n";

and here is the result:

结果如下:

Case #1
I am called.
    Inside the loop: One => 1
    Inside the loop: Two => 2
    Inside the loop: Three => 3
    Inside the loop: Four => 4
    Inside the loop: Five => 5

Case #2
I am called.
    Inside the loop: One => 1
    Inside the loop: Two => 2
    Inside the loop: Three => 3
    Inside the loop: Four => 4
    Inside the loop: Five => 5

They both read call function once. So no different.

他们都读了一次调用函数。所以没有什么不同。

回答by deceze

foreachmakes a copy of the input array and works on that in each iteration. So you can use foreach (do_something_that_returns_an_array() as $key => $val)and it'll call do_something_that_returns_an_array()only once.

foreach制作输入数组的副本并在每次迭代中进行处理。所以你可以使用foreach (do_something_that_returns_an_array() as $key => $val)它只会调用do_something_that_returns_an_array()一次。

回答by alex

I would set up an example to see what happens. Something like...

我会建立一个例子来看看会发生什么。就像是...

function do_something_that_returns_an_array() {
    echo 'I have been called!'; 
    return array('i am an', 'array');
}

As you can see on CodePad, it is only being called once.

正如您在 CodePad 上看到的,它只被调用一次

回答by Steven

I've always assumed that do_something_that_returns_an_array()only runs once because, unlike in the for loop, there's no reason for it to run multiple times. The reason the for loop truth checker runs at the end of every iteration is to allow for very complicated checkers.

我一直假设do_something_that_returns_an_array()只运行一次,因为与 for 循环不同,它没有理由运行多次。for 循环真值检查器在每次迭代结束时运行的原因是允许使用非常复杂的检查器。

As a test, I did the following:

作为测试,我执行了以下操作:

function get_array() {echo 5; return array(1,2,3,4,5);}
foreach(get_array() as $key => $value) {}

The script printed 5 once. Therefore, the function get_array()only evaluates once.

脚本打印 5 一次。因此,该函数get_array()只计算一次。

回答by Valentin Golev

foreach() works with Iterator or IteratorAggregate objects (e.g., arrays and objects implementing the interface). It can't work with immutableobjects. Functions return immutableobjects, so the returning array have to be copied into Iterator object before foreaching (it's made by php itself)

foreach() 与 Iterator 或 IteratorAggregate 对象(例如,实现接口的数组和对象)一起使用。它不适用于不可变对象。函数返回不可变对象,因此返回数组必须在 foreaching 之前复制到 Iterator 对象中(它是由 php 自己制作的)