PHP can use the foreach statement to traverse the array without using for. foreach is a statement specially designed for traversing arrays. It is a commonly used method when traversing arrays. It provides great convenience in traversing arrays. The foreach statement traverses the array regardless of the array subscript, and can be used for discontinuous index arrays and associative arrays with strings as subscripts.
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
php can be traversed using the foreach statement without using for Process arrays.
foreach is a statement specially designed for traversing arrays. It is a commonly used method when traversing arrays. It provides great convenience in traversing arrays. After PHP5, you can also traverse objects (foreach can only be applied for arrays and objects).
The foreach statement traverses the array regardless of the array subscript, and can be used for discontinuous index arrays and associative arrays with strings as subscripts.
The foreach statement has two syntax formats:
Syntax format 1:
foreach ($array as $value){ 语句块; }
Traverse the given $array
Array, assign the value of the current array to $value
in each loop.
Syntax format 2:
foreach ($array as $key => $value){ 语句块; }
Traverse the given $array
array, and assign the value of the current array to $value
, the key name is assigned to $key
.
Explanation:
When the foreach statement loops, the pointer inside the array will move forward one step, so that the next array element will be obtained in the next loop. Stop traversing and exit the loop until it reaches the end of the array.
foreach statement traverses and modifies the array
Example 1:
<?php header("Content-type:text/html;charset=utf-8"); $array= array("香蕉","苹果","梨子","橙子","橘子","榴莲"); foreach ($array as $value) { echo $value . "<br/>"; } ?>
Instance 2:
Generally, when using the foreach statement to traverse an array, it operates on the backup of the array and generally does not affect the array itself.
You can use a reference loop (add & before $value, so that the foreach statement will assign a value by reference instead of copying a value), then operating on the array in the loop body will affect the array itself.
<?php $array= array(1,2,3,4,5,); foreach ($array as &$value) { $value = $value*2; // 元素值乘以2 } var_dump($array) ?>
It can be seen that there is an & before the last element. That is because the $value reference of the last element of the array will still be retained after the foreach loop. We need to use unset() to destroy it.
unset($value); // 最后取消掉引用
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to traverse and process an array in php without using for. For more information, please follow other related articles on the PHP Chinese website!