foreach() has two uses:
1:
foreach(array_name as $value){ statement; }
The array_name here is the name of the array you want to traverse. In each loop, the current element of the array_name array The value is assigned to $value, and the subscript inside the array moves down one step, that is, the next element is obtained in the next loop.
2:
foreach(array_name as $key => $value){ statement; }
The difference between this and the first method is that there is an additional $key, that is, in addition to assigning the value of the current element to $value, the value of the current element The key value will also be assigned to thevariable$key in each loop. The key value can be a subscript value or astring. For example, "0" in book[0]=1, "id" in book[id]="001".
Let's take a look at the second format. In addition to In addition to getting the value of the element in the array like the first format, you can also get theindexvalue of the element and save it to the $key variable. If the index value of the array has not been manually set, return to the system. Default setting value,
Look at the positive example:
First look at a simpleone-dimensional array:
$myArray=array("1"=>"val1","2"="val2","3"=>"val3"); foreach ($myArray as $key=>$val) { print($key."=>".$val.";"); }
The program will output: 1=> ;val1;2=>val2;3=>val3;, next let’s look at a more complicatedtwo-dimensional arraytraversal, the program is as follows:
$myArray=array( "1"=>array("11"=>"val11","12"=>"val12","13"=>"val13"), "2"=>array("21"=>"val21","22"=>"val22","23"=>"val23"), "3"=>array("31"=>"val31","32"=>"val32","33"=>"val33") ); print("
Output Result:
1
32=>val32
33=>val33
##
The above is the detailed content of Detailed explanation of two usage examples of php foreach. For more information, please follow other related articles on the PHP Chinese website!