PHP array traversal method (foreach, list, each)

Source: Internet
Author: User
The most flexible things in php are arrays, and a lot of data is displayed in arrays. here we will sort out the array traversal method, which can be selected as needed. In PHP, arrays are divided into two types: numerical index arrays and associated arrays.
The numeric index array is the same as the array in C language. the subscript is 0, 1, 2...
The subscript of the correlated array may be of any type, which is similar to the hash and map structures in other languages.

The following describes three methods to traverse joined arrays in PHP:

Method 1: foreach

The code is as follows:


$ Sports = array (
'Football' => 'good ',
'Canonicalization' => 'very well ',
'Running' => 'not good ');
Foreach ($ sports as $ key => $ value ){
Echo $ key. ":". $ value ."
";
?>


Output result:

Football: good
Faster Ming: very well
Running: not good

Method 2: each

The code is as follows:


$ Sports = array (
'Football' => 'good ',
'Canonicalization' => 'very well ',
'Running' => 'not good ');
While ($ elem = each ($ sports )){
Echo $ elem ['key']. ":". $ elem ['value']."
";
?>



Method 3: list & each

The code is as follows:


$ Sports = array (
'Football' => 'good ',
'Canonicalization' => 'very well ',
'Running' => 'not good ');
While (list ($ key, $ value) = each ($ sports )){
Echo $ key. ":". $ value ."
";
?>

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.