Home >Backend Development >PHP Tutorial >Introduction to PHP method of traversing associative array_PHP tutorial

Introduction to PHP method of traversing associative array_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-13 10:32:25832browse

Arrays are divided into two categories in PHP: numeric index arrays and associative arrays. The numeric index array is the same as the array in C language. The subscripts are 0, 1, 2... and the associative array subscripts 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:

foreach

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


Program running result:

football: good
swimming: very well
running: not good


each

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



Program running result: Program running result:

football: good
swimming: very well
running: not good


list & each

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


Program running result:

football: good
swimming: very well
running: not good



www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/755774.htmlTechArticleArrays in PHP are divided into two categories: numeric index arrays and associative arrays. The numeric index array is the same as the array in C language. The subscripts are 0, 1, 2... and the associative array subscripts may be arbitrary...
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