Home > Backend Development > PHP Tutorial > 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
Release: 2016-08-20 09:04:11
Original
1136 people have browsed it

$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>
Copy after login
Copy after login

}
?>

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>
Copy after login
Copy after login

}
?>

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>
Copy after login

or

<code class="php">foreach ($countries as $country) {
    echo current($countries);    //因为current是要传引用的, 这里发生了copy-on-write
}</code>
Copy after login

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

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template