To solve the problem, the foreach loop array will only move the pointer once to the second place,

Source: Internet
Author: User
& Amp; lt ;? Php $ countries [{code...}]; foreach ($ countriesas $ key & amp; gt; $ value) {code ...}}? & Amp; gt;

$ Countries = [

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

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

Print_r (current ($ countries); echo 'next'; print_r (pos ($ countries); next ($ countries); echo PHP_EOL;

}
?>

Reply content:

$ Countries = [

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

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

Print_r (current ($ countries); echo 'next'; print_r (pos ($ countries); next ($ countries); echo PHP_EOL;

}
?>

Defined$countriesAnd in the foreach loop$countriesPoint to the same zval variable, because PHP needs to save memory, and does not need to store the same data in two copies. In this caserefcount2. but if it is changed in the loop$countriesFor example

Foreach ($ countries as & $ country) {$ country = 'China'; // because the value assignment operation is performed here, copy-on-write}

Or

Foreach ($ countries as $ country) {echo current ($ countries); // because current is to be referenced, copy-on-write} occurs here}

Passed the reference and assigned a value, which is triggeredcopy-on-writeOperation, that is, copy the zval to the original zvalrefcountMinus 1.

The current statement is executed every time a loop occurs.copy-on-writeSo each current operation is a new zval.

Same as this answer

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.