A simple PHP pen exam (Advanced required)-PHP source code

Source: Internet
Author: User
The following is a simple PHP pen exam (Advanced required). If you want to go to the interview, please refer to this pen exam. The following is a simple PHP pen exam (Advanced required). If you want to go to the interview, please refer to this pen exam.

Script ec (2); script

Once, a senior gave me a PHP written test. The questions are roughly as follows:

The Code is as follows:
$ Arr = array ('1', '2', '3 ');

Foreach ($ arr as $ key =>&$ val ){}

Foreach ($ arr as $ key => $ val ){}

Var_dump ($ arr );

What is the answer?

After reading it, I will be ready? I don't know where the question is. The difference between the two foreach statements is that one is the address and the other is not the address. Will this affect the result?

The output result is

The Code is as follows:

Array (
0 => string '1' (length = 1)
1 => string '2' (length = 1)
2 => & string '2' (length = 1)
)

Why is the printed data like this? Where did "3" go?
The reason for this is: & the address is correct.

In this way, it is intuitive to use foreach to read arrays.

Then, the loop is the moving reading of the pointer, and because it is an & value, the address is read directly, but the assignment is not simple. So when the first loop ends. $ Val and $ arr [2] refer to the same address. Therefore, if the $ val value is changed, the value of $ arr ['2'] also changes.

If you run the following code:

The Code is as follows:
$ Arr = array ('1', '2', '3 ');

Foreach ($ arr as $ key =>&$ val ){}

Foreach ($ arr as $ key => $ val ){
Var_dump ($ arr );
}
Var_dump ($ arr );

You can see the change process. And the reason for obtaining the previous results

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.