Home >Backend Development >PHP Tutorial >Solve why the foreach loop array only moves the pointer once to the second position.
$countries = [
<code> [ '0' => [ 'id' =>0 ] ], [ '1' => [ 'id' =>1 ] ], </p> <p>];<br>foreach ($countries as $key => $value) {</p> <pre class="brush:php;toolbar:false"><code>print_r(current($countries)); echo '下一个'; print_r(pos($countries)); next($countries); echo PHP_EOL; </code>
}
?>
$countries = [
<code> [ '0' => [ 'id' =>0 ] ], [ '1' => [ 'id' =>1 ] ], </p> <p>];<br>foreach ($countries as $key => $value) {</p> <pre class="brush:php;toolbar:false"><code>print_r(current($countries)); echo '下一个'; print_r(pos($countries)); next($countries); echo PHP_EOL; </code>
}
?>
The already defined $countries
and the $countries
in the foreach loop point to the same zval variable, because PHP wants to save memory and does not need to store the same data twice. At this time, the refcount
in zval is 2. But if $countries
is changed in the loop, for example
<code class="php"> foreach ($countries as &$country) { $country = 'china'; //因为这里进行了赋值操作, 这里发生了copy-on-write }</code>
or
<code class="php">foreach ($countries as $country) { echo current($countries); //因为current是要传引用的, 这里发生了copy-on-write }</code>
Passing a reference and assigning a value triggers the copy-on-write
operation, which is copy-on-write. A copy of the zval will be copied, and the refcount
of the original zval will be reduced by 1.
Every time it loops, current will be executed, so every loop happens copy-on-write
, so every time current operates a new zval.
Looking for this answer together