首页 > 开发 > php > 正文

php如何移动数组内部指针

2017-09-06 15:06:44  来源:网友分享

php的数组都有一个内部指针,指向数组的元素,初始化的时候是第一个,我要便利数组,让内部指针逐个移动

$arr = array ('a', 'b', 'c', 'd', 'e');foreach ($arr as $k => $v) {    $curr = current($arr);    echo "{$k} => {$v} -- {$curr}\n";}

得到结果是

0 => a -- b1 => b -- b2 => c -- b3 => d -- b4 => e -- b

内部指针向后移动了一位就再也没动过了。。。
foreach对这个数组做了什么呢?为什么呢?
我要让指针遍历数组,得到如下结果改怎么做呢?

0 => a -- a1 => b -- b2 => c -- c3 => d -- d4 => e -- e

解决方案

这个问题我在bugs.php.net上回答过: https://bugs.php.net/bug.php?id=63752

1. at the beginning of foreach: ZEND_FE_RESET which increase the refoucnt of $a
2. then FE_FETCH, reset internal pointer of $a
3. then current, current declared to accept a reference, but $a is not a ref and refcount > 1 , then -> separation