当前位置:Gxlcms > PHP教程 > 求解为什么foreach循环数组只会讲指针移动一次到第二位,

求解为什么foreach循环数组只会讲指针移动一次到第二位,

时间:2021-07-01 10:21:17 帮助过:12人阅读

$countries = [

        [
            '0' => [
                'id' =>0
            ]
        ],
        [
            '1' => [
                'id' =>1
            ]
        ],

];
foreach ($countries as $key => $value) {

print_r(current($countries));
echo '下一个'; print_r(pos($countries)); next($countries);
echo PHP_EOL;

}
?>

回复内容:

$countries = [

        [
            '0' => [
                'id' =>0
            ]
        ],
        [
            '1' => [
                'id' =>1
            ]
        ],

];
foreach ($countries as $key => $value) {

print_r(current($countries));
echo '下一个'; print_r(pos($countries)); next($countries);
echo PHP_EOL;

}
?>

已经定义的$countries和foreach循环中的$countries指向的是同一个zval变量, 因为PHP要节省内存,不需要同样的数据存两份。这时候zval中的refcount为2. 但是如果在循环中改变$countries, 比如说


foreach ($countries as &$country) {
    $country = 'china';    //因为这里进行了赋值操作, 这里发生了copy-on-write
}

或者

foreach ($countries as $country) {
    echo current($countries);    //因为current是要传引用的, 这里发生了copy-on-write
}

传了引用, 并且赋值,为触发 copy-on-write 操作, 就是写时复制. 会将zval复制一份, 并把原来的zval的refcount减1.

每次循环时, 都会执行current,所以每次循环都发生copy-on-write, 所以每次current 操作的是一份新的zval.

同求这个答案

人气教程排行