PHP foreach语句引用:重用迭代器时,意外的行为 [英] PHP foreach statement by reference: unexpected behaviour when reusing iterator

查看:97
本文介绍了PHP foreach语句引用:重用迭代器时,意外的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这code产生一个​​意想不到的输出:

this code produce an unexpected output:

$array=str_split("abcde");
foreach($array as &$item)
    echo $item;

echo "\n";
foreach($array as $item)
    echo $item;

输出:

abcde
abcdd

如果使用&放大器; $项目的第二个循环,一切工作正常。

if use &$item for second loop everything works fine.

我不明白这个code将如何影响 $阵列的内容。我认为一个隐含的未设置($头)将删除最后一行,但在哪里呢双 DD 来自?

I don't understand how this code would affect the content of $array. I could consider that an implicit unset($header) would delete the last row but where does the double dd comes from ?

推荐答案

这可以帮助:

$array=str_split("abcde");
foreach($array as &$item)
    echo $item;

var_dump($array);

echo "\n";
foreach($array as $item) {
    var_dump($array);
    echo $item;
}

如您最后一次迭代后看到 $项目 $阵列(<$ C的第4单元$ C>电子)。

在你迭代这个数组和第4单元更改为当前。所以第二个循环的第一次迭代后,这将是 ABCDA 等,以 abcdd 。而在最后一次迭代更改4元至4日,为 D D

After that you iterate over the array and change the 4th element to the current one. So after first iteration of the second loop it will be abcda, etc to abcdd. And in the last iteration you change 4th element to 4th, as d to d

这篇关于PHP foreach语句引用:重用迭代器时,意外的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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