Home > Backend Development > PHP Tutorial > Summary of PHP array traversal methods

Summary of PHP array traversal methods

WBOY
Release: 2016-08-08 09:22:49
Original
898 people have browsed it

Arrays are divided into two categories in PHP: numeric index arrays and associative arrays.
The numerical index array is the same as the array in C language, the subscripts are 0, 1, 2...
The subscript of the associative array may be of any type, similar to hash, map and other structures in other languages.
The following introduces three methods of traversing associative arrays in PHP:
Method 1: foreach

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

Output results:
football: good
swimming: very well
running: not good

Method 2, each

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

Method 3: list & each

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

The above has introduced a summary of the PHP array traversal method, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

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