Comparison _php techniques of several single-dimension array traversal methods in PHP

Source: Internet
Author: User
Copy Code code as follows:

<?php
A
$arr =array (' A ' => ' abc ', ' B ' =>123, ' C ' =>true);
B
$arr =range (' A ', ' d ');
1
for ($i =0; $i <sizeof ($arr); $i + +)
echo $arr [$i]. ', ';
echo ' <br/> ';
2
foreach ($arr as $key)
echo "$key,";
echo ' <br/> ';
3
foreach ($arr as $key => $val)
echo "$key-$val,";
echo ' <br/> ';
4
Reset ($arr);
while ($item =each ($arr)) {
echo $item [' key ']. -'. $item [' value ']. ', ';
}
echo ' <br/> ';
5
Reset ($arr);
while (list ($key, $val) =each ($arr)) {
echo "$key-$val,";
}
echo ' <br/> ';
?>

Use statement a $arr =array (' A ' => ' abc ', ' B ' =>123, ' C ' =>true); The $arr is initialized with an array of numeric indices, and the output is as follows:
, , ,
ABC, 123, 1,
A-ABC, b-123, C-1,
A-ABC, b-123, C-1,
A-ABC, b-123, c-1, using statement b $arr =range (' A ', ' d '); Initialize the $arr to get an associative array, the output is as follows:
A, B, C, D,
A, B, C, D,
0-a, 1-b, 2-c,
0-a, 1-b, 2-c,
0-a, 1-b, 2-c, the For loop only has a limited number of numeric indexes; the for and foreach traversal end does not require the reset () operation of the data for the next traversal, and the each method requires.

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.