php - 在 PHP 7 中处理 foreach by-ref

标签 php arrays foreach pass-by-reference php-7

到目前为止,我们一直在使用 PHP 5.5,代码似乎一切都顺畅。由于将其升级到 7,大多数 foreach() 似乎都存在不一致的行为。

例如:考虑下面的片段:

$array = array('a', 'b', 'c');
self::testForeach($array);
.
.
.
// $array is passed by reference
public static function testForeach(&$array) {

  foreach ($array as $key => $val) {
    //produces a, b as an output in PHP 5
    //produces a, b, c as an output in PHP 7
    var_dump($val);

    if ($val == 'b') {
      //remove 'c' from the array
      unset($array[2]);
    }
  }
}

PHP 5.5 中的行为:

$array is passed by reference to testForeach() function. So removing "c" from $array inside the loop would directly modify the original array. Hence, the iterated values would be a, b and not c as it gets removed from the array in between.

PHP 7 中的行为:

$array is passed by reference to testForeach() function. When $array is looped over foreach(), a copy is made say $arrayCopy (according to the doc) which is being iterated over the loop. So removing "c" value from $array would have no effect and will loop all the values contained in the $arrayCopy. Hence the output - a, b, c.

将 foreach 更改为 pass-by-ref 对我来说不是一个解决方案,因为我的项目中有太多的 foreach,我无法 grep 和修改它们中的每一个。

在最新版本中是否对此类行为进行了任何其他处理。任何可以突出显示它们的工具/解析器?

有什么提示/想法吗?

谢谢!

最佳答案

仅当您通过引用循环数组时:foreach ( $array as $key => &$val ) {

Afaik 然后没有制作副本。 http://php.net/manual/en/control-structures.foreach.php

警告:在这种情况下,$val 仍然是指向数组最后一个元素的指针,最佳做法是取消设置它。

foreach ( $array as $key => &$val ) {


<?php

$array = array();
testForeach( $array );

// $array is passed by reference
function testForeach( &$array )
{
    $array = array( 'a', 'b', 'c' );
    foreach ( $array as $key => &$val ) {
        //produces a, b as an output in PHP 5
        //produces a, b, c as an output in PHP 7
        var_dump( $val );

        if ( $val == 'b' ) {
            //remove 'c' from the array
            unset( $array[ 2 ] );
        }
    }
    unset($val);
}

关于php - 在 PHP 7 中处理 foreach by-ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39530753/

相关文章:

c# - 如何在 foreach 循环中的每次迭代后进行延迟?

php - 无法使用 php 访问 session 数组

php - 没有 plus 是否仍然可以使用 Google OAuth?

C# 和匿名对象数组

java - 如何将字节数组转换为 double 组并返回?

php - 使用带有重复 ID 的联结表会导致 php foreach 循环中的 sql 查询困惑

php - "undefined function exif_read_data()"错误仅通过 Cron

php - 如何在使用 PHP 导入 SQL 之前正确转义 CSV 文件

python - 将二维数组乘以一维数组

java - 如何使用流和 lambda 转换包含简单 for 循环的 java 代码?