Home > Backend Development > PHP Problem > Detailed explanation of two methods of traversing arrays using foreach() in PHP

Detailed explanation of two methods of traversing arrays using foreach() in PHP

醉折花枝作酒筹
Release: 2023-03-08 21:52:01
Original
3115 people have browsed it

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.

Detailed explanation of two methods of traversing arrays using foreach() in PHP

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(&#39;content-type:text/html;charset=utf-8&#39;);
$arr = array(&#39;苹果&#39;,&#39;草莓&#39;,&#39;葡萄&#39;);
foreach($arr as $value){
echo $value."<br>";
}
?>
Copy after login

Output result:

苹果
草莓
葡萄
Copy after login

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(&#39;content-type:text/html;charset=utf-8&#39;);
$arr = array(&#39;苹果&#39;,&#39;草莓&#39;,&#39;葡萄&#39;);
foreach($arr as $k=>$v){
echo $k."=>".$v."<br>";
}
?>
Copy after login

Output result:

0=>苹果
1=>草莓
2=>葡萄
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template