PHP的current()函数是否返回数组的副本或引用?


Does the PHP current() function return a copy or reference of array?

我创建了一个简单的测试用例,它复制了我遇到的一个问题。

我正在使用next()current()函数遍历二维数组,并且我想将数组指针设置为特定位置。因此,给定一个变量名为$food的二维数组,其数组结构如下:

array
  0 => <-- POINTER LOCATION
    array
      0 => string 'apple' <-- POINTER LOCATION
      1 => string 'orange'
  1 => 
    array
      0 => string 'onion'
      1 => string 'carrot'

…以及下面的代码片段:

// move the inner array's pointer once
$should_be_orange = next(current($food));
// now check that inner array's value
$should_still_be_orange = current(current($food));

…为什么$should_be_orange的值是"橙色",而$should_still_be_orange的值是"苹果"?这是因为current()函数返回内部数组的副本,谁的指针得到迭代,然后销毁(留下原始数组不变)?或者我只是做错了什么,我没有意识到?

在问题的根源,你如何移动内部数组的指针,因为你不知道外部数组的键(并且必须使用current()函数来获得外部数组的指针位置)?

实际上current()返回的是数组中的一个元素。在您的示例中,该元素也是一个数组,这就是为什么next()在您的代码中可以正常工作。您的next()不能在$food数组上工作,而是在$food[0]的副本上工作,由current()

返回

不能在参数中传递函数,只能传递变量,因为参数是引用:

function current(&$array) {...}
function next(&$array) {...}

所以正确的语法是:

// move the inner array's pointer once
$tmp = current($food);
$should_be_orange = next($tmp);
// now check that inner array's value
$tmp = current($food);
$should_still_be_orange = current($tmp);
                 ^^^^^^ NO! It should be "apple" ! When you do next($tmp) it will be orange !

演示:http://codepad.viper - 7. - com/yzfeaw

文档:

  • Next(和美元数组)
  • 当前(和数组美元)

当你正在学习PHP时,你应该使用命令显示所有错误:

error_reporting(E_ALL);

使用这个u应该收到通知:

Strict Standards: Only variables should be passed by reference in (...) on line (...)

(我认为这个答案需要复习,因为英语语法)