Bugs caused by the PHP array foreach reference

Source: Internet
Author: User

<?PHP$arr=Array(' A ', ' B ', ' C ');foreach($arr  as&$v) {}foreach($arr  as $v) {}Var_dump($arr);/*The result is: Array (3) {[0]=> string (1) "A" [1]=> string (1) "B" [2]=> &string (1) "B"}*///The first foreach assigns the value of the array to $v in the same way as a reference assignment. $arr=Array(' A ', ' B ', ' C ');foreach($arr  as&$v) {}Var_dump($v);//at this point, the value of $v is C, which is the reference assignment, $v points to the address space of the string C. The second foreach assigns the values of the array to the $v in the same way as the copy assignment. Since the current $v points to the address space of C, changing the value of $v changes the value of the address space occupied by C. $arr=Array(' A ', ' B ', ' C ');foreach($arr  as&$v) {}foreach($arr  as $v) {    Var_dump($arr); Break;}//The first assignment assigns a value of a to $v, and the value of the address space of the original C becomes a, when the array (' A ', ' B ', ' a '). And so the first assignment c->a, the second assignment is a->b, the third assignment is b->b,//so the final result is an array (' A ', ' B ', ' B '). 

The problem is that the foreach itself is an assignment process, when the first foreach ends $value and $arr[2] Two variables point to $arr[2], and the second time when foreach is essentially an assignment behavior, that is, $  Value = $arr [0; This makes $arr[2] the same as the second time $arr[2] = $arr [1] causes $arr [2] Each cycle will be re-assigned value

Bug caused by the PHP array foreach reference

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.