A brief discussion on the pit _php example about foreach using reference variable in PHP

Source: Internet
Author: User
Tags php foreach

Write PHP for many years, but still make a low-level error, today encountered a foreach reference variable when the pit, PHP version of the 5.6.12 code is as follows:

<?php
$arr = [' A ', ' B ', ' C ', ' d ', ' e '];
foreach ($arr as $i =>& $a) {
  $a = $a. ' _ '. $a;
  echo $a. ' <br> ';
}
Echo '  
 

Output results

First saw the result of the second foreach output is very puzzling, how can output two d_d?

Think about it, because the $a scope of PHP foreach is a local variable of the entire function, which is still valid outside the loop, rather than being enclosed within the loop,

So when the second foreach is executed, the $a is not a new variable, but it still points to an address reference to the 5th element of the $arr array.

When the second foreach is in the loop, it is actually giving a value to the 5th element of the $arr array,

Specific assignment,

First time: A_a assignment to the 5th element, the result is: [A_a, B_b, C_c, D_d,a_a]

Second time: B_b assignment to the 5th element, the result is: [A_a, B_b, C_c, D_d,b_b]

Third time: C_c assignment to the 5th element, the result is: [A_a, B_b, C_c, D_d,c_c]

Fourth time: D_d assigned to the 5th element, the result is: [A_a, B_b, C_c, D_d,d_d]

Fifth time: Now because the Fifth element has become d_d and D_d assigned to the 5th element, the result is: [A_a, B_b, C_c, D_d,d_d]

Solution:

1. Try not to use the same cycle variable name;

2. unset ($a) before the end of each use or reuse; handling, removing address application

Or use the code example above:

$arr = [' A ', ' B ', ' C ', ' d ', ' e '];
foreach ($arr as $i =>& $a) {
  $a = $a. ' _ '. $a;
  echo $a. ' <br> ';
}
Echo '  
 

Output results:

It's normal now, and these little details must be noticed.

The above is a small series for everyone to talk about the use of the reference variable in PHP, all the contents of the pit, I hope that we support the cloud-Habitat Community ~

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.