Do you really know PHP foreach? A very clear example of usage explained

Source: Internet
Author: User
Tags php foreach
In daily development, the foreach traversal array using PHP is almost standard. It can be very convenient to traverse the array of key and value. but do you really know the personality of it?

How does PHP foreach work?

The following PHP Chinese network with examples to explain the use of PHP foreach and considerations.

For example: There are the following arrays:

$array = Array (1,2,3,4,5);

Requires that each element value in the $array array be added 1

Generally, we can use the following processing methods, method one:

foreach ($array as $key = + $value) {    $array [$key] = $value +1;}

You can also use the following methods, method two:

foreach ($array as & $value) {    $value = $value +1;}

In general, there are no problems with these two formulations, and the results are the same. However, when we need to use $value in the next procedure, such as assigning a new value of 8 to $value, the result of Method 2 will be changed strangely.

foreach ($array as & $value) {    $value = $value +1;} $value = 8;

When printing Print_r ($array), we want the output

Array ([0] = 2 [1] = 3 [2] = 4 [3] = 5 [4] = 6);

But it will actually output:

Array ([0] = 2 [1] = 3 [2] = 4 [3] = 5 [4] = 8),

In other words, the last element becomes 8.

Why is there such a situation?

In fact, the $value in method Two is a reference, and it is global, and when foreach executes, the reference to $value is still valid, which will cause any modifications to the $value outside of foreach to affect the last element in the $array.

So how do we solve this problem?

The method is very simple, since $value is still valid outside of foreach, then we can give the $value to unset after the completion of the foreach execution. The improved code is as follows:

foreach ($array as & $value) {    $value = $value +1;} Unset ($value); $value = 8;

Now the program output $array the last element is 6, no longer affected by $value modification.

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.