PHP array traversal method daqo of foreach list each

  • 2020-03-31 20:51:06
  • OfStack

There are two types of arrays in PHP: numerically indexed arrays and associative arrays.
Where the numeric index array is the same as the array in C language, the index is 0,1,2...
The index of associative array may be of any type, similar to the structure of hash, map and so on in other languages.

Here are three ways to traverse associative arrays in PHP:

Method 1: foreach

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

Output results:

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

Related articles: