Home > Backend Development > PHP Tutorial > Do you really understand PHP foreach? Very clear usage examples

Do you really understand PHP foreach? Very clear usage examples

西门大官人
Release: 2023-04-03 07:14:02
Original
2056 people have browsed it

In daily development, using PHP's foreach to traverse arrays is almost standard. It can very conveniently traverse the keys and values ​​of the array. But do you really understand its personality?

How to use PHP foreach?

The following PHP Chinese website uses examples to explain the usage and precautions of PHP foreach.

For example: There is the following array:

$array = array(1,2,3,4,5);
Copy after login

Requires the value of each element in the $array array to be increased by 1

Usually, we can use the following Processing method, method one:

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

You can also use the following method, method two:

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

Under normal circumstances, these two writing methods will not cause any problems, and the results will be the same. But when we need to use $value in the next program, such as assigning a new value of 8 to $value, the results of method 2 will change strangely.

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

When print_r($array) is printed, we hope to output

Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 );
Copy after login

but it will actually output:

Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 8 ),
Copy after login

In other words, the last element becomes 8 .

Why is there such a situation?

In fact, $value in method 2 is a reference, and it is global. When foreach is executed, the reference to $value is still valid, which will result in any reference to $value outside foreach. Modifications will affect the last element in $array.

So how to solve this problem?

The method is very simple. Since $value is still valid outside foreach, we can unset $value after foreach execution is completed. The improved code is as follows:

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

Now the program outputs the last element of $array as 6, which is no longer affected by $value modification.


The above is the detailed content of Do you really understand PHP foreach? Very clear usage examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template