Home  >  Article  >  Backend Development  >  Solve why the foreach loop array only moves the pointer once to the second position.

Solve why the foreach loop array only moves the pointer once to the second position.

WBOY
WBOYOriginal
2016-08-20 09:04:111089browse

$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>

}
?>

Solve why the foreach loop array only moves the pointer once to the second position.

Reply content:

$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>

}
?>

Solve why the foreach loop array only moves the pointer once to the second position.

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn