PHP Address Characters &

Source: Internet
Author: User

I have a very strange problem today.

$arr =[' A ', ' B ', ' C '];foreach ($arr as & $v) {}foreach ($arr as $v) {}var_dump ($arr); unset ($v); Var_dump ($arr);

This code believes that I can see that the output is ABC

But the result is:

Array (size=3) 0 = String ' a ' (length=1) 1 = = String ' B ' (length=1) 2 = &string ' B ' (length=1) array (siz e=3) 0 = String ' a ' (length=1) 1 = = String ' B ' (length=1) 2 = String ' B ' (length=1) focuses on

2 = &string ' B ' (length=1) This place is equivalent to $v assigned to $ARR[2]

The reason for this is that the &php address character

Let's take a look at the basic usage of &:

$b = $c = 1; $a = & $b; $a = 2;echo "b= $b, c= $c \ n"; $a = & $c; $a = n, $a = 200;echo "b= $b, c= $c \ n"; unset ($a); $a = 500;ec Ho "b= $b, c= $c \ n"; After a $ A is specified as a $b reference, unless you specify another reference again, or unset ($a), changing $ A will change the value of the corresponding $b.

For you this foreach, is the same truth, you take the loop apart, this is the way:

$v = & $arr [0]; $v = & $arr [1]; $v = & $arr [2];

The loop runs to the last time, $v is a reference to $arr[2], so it is equivalent to this form:

$arr [0] = A; $arr [1] = b; $v = & $arr [2]; $arr [2] = B;var_dump ($arr);

It is not difficult to understand why Var_dump will print a & symbol on the last key-value pair.

PHP address character &

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.