php There are two ways to write foreach, namely: 1. "foreach (iterable_expression as $value)"; 2. "foreach (iterable_expression as $key => $value)".
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
What is the writing method of php foreach?
The foreach syntax structure provides a simple way to traverse an array. foreach can only be applied to arrays and objects. If you try to apply it to variables of other data types, or uninitialized variables, an error message will be issued. There are two syntaxes:
foreach (iterable_expression as $value) statement foreach (iterable_expression as $key => $value) statement
The first format iterates over the given iterable_expression iterator. Each time through the loop, the value of the current cell is assigned to $value.
The second format does the same thing, except that the key name of the current unit will also be assigned to the variable $key in each loop.
Note that foreach will not modify the internal pointer of the array used by functions like current() and key().
You can also customize the traversal object.
You can easily modify the elements of an array by adding & before $value. This method assigns by reference rather than copying a value.
<?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } // $arr is now array(2, 4, 6, 8) unset($value); // 最后取消掉引用 ?>
WARNING
The $value reference of the last element of the array remains after the foreach loop. It is recommended to use unset() to destroy it. Otherwise you will encounter the following situation:
<?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } // 现在 $arr 是 array(2, 4, 6, 8) // 未使用 unset($value) 时,$value 仍然引用到最后一项 $arr[3] foreach ($arr as $key => $value) { // $arr[3] 会被 $arr 的每一项值更新掉… echo "{$key} => {$value} "; print_r($arr); } // ...until ultimately the second-to-last value is copied onto the last value // output: // 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 ) // 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 ) // 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 ) // 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 ) ?>
You can traverse the values of array constants by reference:
<?php foreach (array(1, 2, 3, 4) as &$value) { $value = $value * 2; } ?>
Note:
foreach does not support suppression with "@" Error message capabilities.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What is the writing method of php foreach. For more information, please follow other related articles on the PHP Chinese website!