This article will give you a detailed understanding of the two methods of using foreach() to traverse arrays in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Method 1: foreach(array name as custom variable){}
foreach will The elements in the array assign the value of the array to a custom variable in each loop. When this variable is used in each loop, the value in the array during the current loop is used; regardless of whether the array is an index array or an associative array. It will not affect the value of foreach; we can look at an example:
<?php header('content-type:text/html;charset=utf-8'); $arr = array('苹果','草莓','葡萄'); foreach($arr as $value){ echo $value."<br>"; } ?>
Output result:
苹果 草莓 葡萄
By using this method to traverse the array, we can only get the contents of the array, but there is no way to get it. Index value, the index value can be output through method 2.
Method 2: foreach (array name as variable name of key => variable name of value){}
The difference from the first one is , In addition to assigning the value of the current element to $value, the key value of the current element will also be assigned to $key each time it is looped. The key value may be a subscript or a string. We can deepen our impression through an example:
<?php header('content-type:text/html;charset=utf-8'); $arr = array('苹果','草莓','葡萄'); foreach($arr as $k=>$v){ echo $k."=>".$v."<br>"; } ?>
Output result:
0=>苹果 1=>草莓 2=>葡萄
[Recommended learning: "PHP Video Tutorial"]
The above is the detailed content of Detailed explanation of two methods of traversing arrays using foreach() in PHP. For more information, please follow other related articles on the PHP Chinese website!