This article mainly introduces foreach in PHP, in addition to the ordinary foreach(array_expression_r_r as $value){} format, another way of writing foreach, foreach(array_expression_r_r as $key => $value){}.
As we all know, use the simple foreach(array_expression_r_r as $value){} format, such as:
<?php $arr=array("one","two","three"); foreach($arr as $a){ echo $a; } ?>
foreach executes the reset(array) function by itself, points the internal pointer of the array to the first element, and returns the value of this element. Afterwards, the execution is continuously moved backward and the arr array is output.
However, if I want to operate on the subscripts of each element while using foreach to traverse arr, I have to use the foreach(array_expression_r_r as $key => $value){} structure.
For example, the following program:
<?php $arr=array("one","two","three"); foreach($arr as $key=>$value){ echo "arr[$key]=$value<br>"; } ?>
Using $key, you can get the subscript of each element during the loop, which is this element position in this array.
Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.
The above has introduced the foreach structure, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.