A complete list of methods for traversing associative arrays in PHP (foreach, list, each, list)

伊谢尔伦
Release: 2023-03-11 07:06:01
Original
2497 people have browsed it

In PHPArraysare divided into two categories: numeric indexedarrays and associative arrays.

The numeric index array is the same as the array in C language, the subscript is 0, 1, 2...
And the associative array subscript may be Any type, similar to hash, map and other structures in other languages.


The following introduces several methods of traversing associative arrays in PHP:
Method 1: foreach

foreach () is the simplest and most effective method for traversing data in an array.

<?php 
$sports = array( 
&#39;football&#39; => &#39;good&#39;, 
&#39;swimming&#39; => &#39;very well&#39;, 
&#39;running&#39; => &#39;not good&#39;); 
foreach ($sports as $key => $value) { 
echo $key.": ".$value."<br />"; 
?>
Copy after login

Output result:

football: good 
swimming: very well 
running: not good
Copy after login

Method 2: each

<?php 
$sports = array( 
&#39;football&#39; => &#39;good&#39;, 
&#39;swimming&#39; => &#39;very well&#39;, 
&#39;running&#39; => &#39;not good&#39;); 
while ($elem = each($sports)) { 
echo $elem[&#39;key&#39;].": ".$elem[&#39;value&#39;]."<br />"; 
?>
Copy after login

Method 3: list & each

<?php 
$sports = array( 
&#39;football&#39; => &#39;good&#39;, 
&#39;swimming&#39; => &#39;very well&#39;, 
&#39;running&#39; => &#39;not good&#39;); 
while (list($key, $value) = each($sports)) { 
echo $key.": ".$value."<br />"; 
?>
Copy after login

Method 4: Use while() with list() and each().

<?php
    $urls= array(&#39;aaa&#39;,&#39;bbb&#39;,&#39;ccc&#39;,&#39;ddd&#39;);
    while(list($key,$val)= each($urls)) {
      echo "This Site url is $val.<br />";
    }
?>
Copy after login

Display results:

This Site url is aaa
This Site url is bbb
This Site url is ccc
This Site url is ddd
Copy after login
Copy after login

Method 5: for()

<?php
    $urls= array(&#39;aaa&#39;,&#39;bbb&#39;,&#39;ccc&#39;,&#39;ddd&#39;);
    for ($i= 0;$i< count($urls); $i++){
      $str= $urls[$i];
      echo "This Site url is $str.<br />";
    }
?>
Copy after login

Display results:

This Site url is aaa
This Site url is bbb
This Site url is ccc
This Site url is ddd
Copy after login
Copy after login



The above is the detailed content of A complete list of methods for traversing associative arrays in PHP (foreach, list, each, list). For more information, please follow other related articles on the PHP Chinese website!

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