Home >Backend Development >PHP Tutorial >A complete list of methods for traversing associative arrays in PHP (foreach, list, each, list)
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( 'football' => 'good', 'swimming' => 'very well', 'running' => 'not good'); 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( 'football' => 'good', 'swimming' => 'very well', 'running' => 'not good'); while ($elem = each($sports)) { echo $elem['key'].": ".$elem['value']."<br />"; ?>
Method 3: list & each
<?php $sports = array( 'football' => 'good', 'swimming' => 'very well', 'running' => 'not good'); while (list($key, $value) = each($sports)) { echo $key.": ".$value."<br />"; ?>
Method 4: Use while() with list() and each().
<?php $urls= array('aaa','bbb','ccc','ddd'); 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('aaa','bbb','ccc','ddd'); 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!