PHP traversal Associative array method Daquan (foreach,list,each,list)

Source: Internet
Author: User
in PHP, arrays are divided into two categories: numbersIndex arrays and associative arrays.

Where the numeric index array is the same as the array in the C language, the subscript is for 0,1,2 ...
Associative array subscripts may be of any type, similar to Hash,map in other languages.


Here are a few ways to iterate through associative arrays in PHP:
Method 1:foreach

foreach () is the simplest and most efficient way to iterate through the 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:while () and list () are used with each ().

<?php    $urls = Array (' AAA ', ' BBB ', ' CCC ', ' ddd ');    while (list ($key, $val) = each ($urls)) {      echo ' This Site URL is $val. <br/> ";    }? >

Show Results:

This site URL is aaathis site URL was bbbthis site URL is cccthis 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/>";    }? >

Show Results:

This site URL is aaathis site URL was bbbthis site URL is cccthis site URL is ddd

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.