PHP array foreach reference problem

Source: Internet
Author: User

<?php$arr = Array (' 1 ', ' 2 '), foreach ($arr as & $value) {}foreach ($arr as $value) {    var_dump ($value);}

Output

string(1) "1"string(1) "1"

Let's just say it, put it foreach into an assignment.

foreach($arr as &$value) {    //noop}

is roughly

#begin first foreach$value = &$arr[0];//noop$value = &$arr[1];//noop#end foreach

If you print $arr, you will see

array(2) {  [0]=>  string(1) "1" [1]=> &string(1) "2"}

$valuethat is, still $arr[1] the reference (alias)

And then we'll take the second foreach apart.

#begin second foreach$value = $arr[0];//note: 由于$value <=> &$arr[1], 此时$arr[1]被赋值成为$arr[0],也就是1var_dump($value);//1$value = $arr[1];//相当于$arr[1] = $arr[1]; 没有实际效果var_dump($value);//1#end foreach

The solution is never to use &

Or honestly follow the official website's instructions, use unset to dereference

  <?php  $arr = array (1, 2, 3, 4);  $arr as & $value) {  $value =  $value * 2;} //$arr is now Array (2, 4, 6, 8) unset (  $value); //break the reference and the last Element?>  span>                 
 

PHP array foreach reference problem

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.