PHP Traversal Array

Source: Internet
Author: User

1. Use for loop traversal, for indexed arrays

$arr = Array (1,2,3,4,5,6,7,8,9);
For ($i =0;count ($arr); $i + +); {
echo $arr [$i]. " <br> ";
}

2. Using foreach to iterate through an array can be used for indexes and associations
Index
$arr = Array (1,2,3,4,5,6,7,8,9);
foreach ($arr as $v) {
echo $v. " <br> ";
}

Association
$arr = Array ("One" =>1, "=>2", "three" =>3, "four" =>4);
foreach ($arr as $v) {
echo $v. " <br> ";
}

foreach ($arr as $k = = $v) {
echo $v. " <br> ";
echo $k. " <br> ";
echo "{$k}--{$v}<br>";
}

3. Use the list () and each () method to iterate through an array

Each method is called multiple times to remove all elements from the array.
List method
List ($a, $b) = Array ("One", 1);
echo $a;

Two mates array traversal
$arr = Array ("One" =>1, "=>2", "three" =>3, "four" =>4);

while (list ($k, $v) =each ($arr)) {
echo "{$k}--{$v}<br>";
}

4. Iterating through the array using pointers

$arr = Array ("One" =>1, "=>2", "three" =>3, "four" =>4);
Echo current ($arr); Remove the value of the element that the current pointer points to
echo Key ($arr); Takes out the index of the current pointer to the element
Next ($arr); Adjust the pointer back
Prev ($arr); Adjust the pointer up
End ($arr); Adjust the pointer to the last
Reset ($arr); Reset the pointer

while (Next ($arr)) {
Echo current ($arr);
echo Key ($arr);
}

do{
Echo current ($arr);
echo Key ($arr);
}while (Next ($arr))

PHP Traversal Array

Related Article

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.