Home  >  Article  >  Backend Development  >  A complete list of methods for traversing associative arrays in PHP (foreach, list, each, list)

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

伊谢尔伦
伊谢尔伦Original
2017-06-22 15:47:302482browse

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 />"; 
?>

Output result:

football: good 
swimming: very well 
running: not good

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 />"; 
?>

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 />"; 
?>

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 />";
    }
?>

Display results:

This Site url is aaa
This Site url is bbb
This Site url is ccc
This Site url is ddd

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 />";
    }
?>

Display results:

This Site url is aaa
This Site url is bbb
This Site url is ccc
This Site url is ddd



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!

Statement:
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