Turn to the foreach page of the PHP document and write this:
the foreach syntax structure provides an easy way to iterate through an array. foreach can only be applied to arrays and objects, if you try to apply a variable to another data type, or an uninitialized variable will emit an error message. There are two kinds of syntax:
foreach (array_expression as $value) Statementforeach (array_expression as $key = $value) statement
The first format iterates through the given array of array_expression . In each loop, the value of the current cell is assigned to the $value and the pointer inside the array is moved forward one step (so the next cell in the next loop will be taken).
The second format does the same thing, except that the key name of the current cell is assigned to the variable $keyin each loop. ”
Then "The first format iterates over the given array of array_expression ." In each loop, the value of the current cell is assigned to the $value and the pointer inside the array is moved forward one step (so the next cell in the next loop will be taken). " what does that mean?" This means that using foreach to iterate through an array is to manipulate a copy of the specified array, rather than the array itself. Like there is a clone of you, others on the cloning of you regardless of how to kick, you also have no influence.
For example:
foreach ($array as $k = = $v) {
$v = 1;
}
The modification of this method is not $array itself, it is an array that modifies its copy, although the same but not $array. So it has no effect on $array.
So what do we do? To do this:
foreach ($array as $k = = $v) {
$array [$k] = 1;
}
Although $k and $v are also copied, the value of the copied $k is the same as the $k value of the original array, so this can be accomplished.
There is also a more advanced approach: You can easily modify the elements of an array by adding & to it before $v . This method assigns a value to a reference instead of copying a value. For example:
foreach ($array as & $v) {
$v = 1;
}
Unset ($v); Finally, remove the reference
This will also be successful.
Problems with using foreach to change the value of an array in PHP