When foreach uploads a reference, is there a bug?

Source: Internet
Author: User
$ Aarray (1, 2, 3); var_dump ($ a); foreach ($ aas & amp; $ B) {} var_dump ($ ); foreach ($ aas $ B) {var_dump ($ B) ;}the following is the result array (3) {[0] & amp; gt; int (1) from 5.2 to 7.0) [1] & amp; gt; int (2) [2] & amp; gt; int (3)} array (3 )...

$ A = array (1, 2, 3 );
Var_dump ($ );
Foreach ($ a as & $ B ){}
Var_dump ($ );
Foreach ($ a as $ B ){
Var_dump ($ B );
}

The following is the result from 5.2 to 7.0.

Array (3) {[0] => int (1) [1] => int (2) [2] => int (3 )}
Array (3) {[0] => int (1) [1] => int (2) [2] =>& Int (3)}
Int (1) int (2)Int (2)

See http://3v4l.org/PXsWr for output of earlier versions

Is this a php bug?

Reply content:

$ A = array (1, 2, 3 );
Var_dump ($ );
Foreach ($ a as & $ B ){}
Var_dump ($ );
Foreach ($ a as $ B ){
Var_dump ($ B );
}

The following is the result from 5.2 to 7.0.

Array (3) {[0] => int (1) [1] => int (2) [2] => int (3 )}
Array (3) {[0] => int (1) [1] => int (2) [2] =>& Int (3)}
Int (1) int (2)Int (2)

See http://3v4l.org/PXsWr for output of earlier versions

Is this a php bug?

Shouldn't I search for it before asking a question... refer to foreach pointer

The reason for this phenomenon is that both foreach uses $ B, while the foreach process first assigns a value, so in the first step of the second loop, will copy the first item of the array to the pointer pointing to the last item, so the last item of the array changes

$bIn the secondforeachIs equivalent&$a[2], So the Tragedy --$a[2]Modified

This is what I do not likeforeachAnd prefer to usearray_walkCause:

$a = array(1,2,3);var_dump($a);array_walk($a, function(&$b){   // do something});var_dump($a);array_walk($a, function($b){    var_dump($b);    // => int(1) int(2) int(3)});

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.