The use of foreach () in PHP
foreach () has two uses:
1:
| The code is as follows |
Copy Code |
foreach (Array_Name as $value)
{
Statement
} |
The array_name here is the array name you want to traverse, each time the value of the current element of the Array_Name array is assigned to the $value, and the subscript inside the array is moved down one step, which is the next loop to get the next element.
2:
| The code is as follows |
Copy Code |
foreach (Array_Name as $key => $value)
{
Statement
} |
The difference between this and the first method is the addition of a $key, in which the key value of the current element is assigned to the variable $key in every loop, except for assigning the value of the current element to $value. The key value can be either a subscript value or a string. For example, "0" in Book[0]=1, "id" in book[id]= "001".
Look at the following example:
| The code is as follows |
Copy Code |
|
$arr = Array (
Array (' ID ' => 1, ' name ' => ' name1 '),
Array (' ID ' => 2, ' name ' => ' name2 '),
);
foreach ($arr as $obj) {
$obj [' id '] = $obj [' id '];
$obj [' name '] = $obj [' name ']. '-modify ';
}
Print_r ($arr); Results of output
Array (
[0] => Array (
[ID] => 1
[Name] => name1
)
[1] => Array (
[ID] => 2
[Name] => name2
)
) |
Observations can be found that the $arr operation does not affect the $arr element in the Foreach loop, so the assignment here is to pass a value instead of a reference. What if you need to modify the value of the elements in the $arr? You can add a "&" symbol in front of the variable, for example:
| The code is as follows |
Copy Code |
|
foreach ($arr as & $obj) {
$obj [' id '] = $obj [' id '];
$obj [' name '] = $obj [' name ']. '-modify ';
} |
To see another example, the array contains object,
| The code is as follows |
Copy Code |
|
$arr = Array (
(object) (Array (' ID ' => 1, ' name ' => ' name1 ')),
(object) (Array (' ID ' => 2, ' name ' => ' name2 ')),
);
foreach ($arr as $obj) {
$obj->name = $obj->name. '-modify ';
}
Print_r ($arr); Results of output
Array
(
[0] => StdClass Object
(
[ID] => 1
[Name] => name1-modify
)
[1] => StdClass Object
(
[ID] => 2
[Name] => name2-modify
)
)
|
At this point you can see that the object objects in the original array have been modified, so the assignment here is a reference rather than a pass value
To synthesize the above, the conclusion: If the array contains a common type of elements is to use the value of the way, the object type element is used to address the way.