Functions of PHP Traversal array and its usage summary

Source: Internet
Author: User

1. foreach ()

foreach () is the simplest and most efficient way to iterate through the data in an array.

#example1:

<?php$colors= Array (' Red ', ' blue ', ' green ', ' yellow '); foreach ($colorsas $color) {echo "Do you like $color? <br/> ";}? >

Show Results:

Like red?
Do you like blue?
Do you like green?
Do you like yellow?

2. while ()

while () is usually used in conjunction with list (), each ().

#example2:

<?php$colors= Array (' Red ', ' blue ', ' green ', ' yellow '), while (List ($key, $val) = each ($colors)) {echo] other list of $ Val.<br/> ";}? >

Show Results:

Other list of red.
Other list of blue.
Other list of green.
Other list of yellow.

3. for ()

#example3:

<?php$arr= Array ("0" = "Zero", "1" = "One", "2" and "one"); for ($i = 0; $i < count ($arr); $i + +) {$str = $arr [$i]; echo "The number is $str. <br/>";}? >

Show Results:

The number is zero.
The number is one.
The number is a.

========= The following is a description of the function ==========

Key ()

Mixed key (array Input_array)

The key () function returns the keys element at the current pointer position in Input_array.

#example4

    1. <?php$capitals= Array ("Ohio" = "Columbus", "towa" = "Des Moines", "Arizona" and "Phoenix"); Echo <p> Can you name the capitals of these states?</p> ", while ($key = key ($capitals)) {echo $key." <br/> "; next ($capitals);//each key () call does not push the pointer. To do this, use the next () function}?>

Show Results:

Can you name the capitals of these states?
Ohio
Towa
Arizona

Reset ()

Mixed reset (array Input_array)

The reset () function is used to set the Input_array pointer back to the beginning of the array. This function is often used when you need to view or work with the same array multiple times in a script, and this function is often used when sorting ends.

#example5-Append code on #example1

<?php$colors= Array (' Red ', ' blue ', ' green ', ' yellow '); foreach ($colorsas $color) {echo "Do you like $color? <br/> ";} Reset ($colors), while (List ($key, $val) = each ($colors)) {echo "$key + = $val <br/>";}? >

Show Results:

Like red?
Do you like blue?
Do you like green?
Do you like yellow?
0 = Red
1 = Blue
2 = Green
3 = Yellow

Note: Assigning an array to another array resets the original array pointer, so in the example above, if we assign the $colors to another variable inside the loop, it will cause an infinite loop.
For example will $s 1 = $colors; Add to the while loop and execute the code again, and the browser will display the results endlessly.

each ()

Array each (array Input_array)

The each () function returns the input array's current key/value pair and advances the pointer to a position. The returned array contains four keys, key 0 and key contain the key names, and key 1 and value contain the corresponding data. Returns False if each () is executed before the pointer is at the end of the array.

#example6

<?php$capitals= Array ("Ohio" = "Columbus", "towa" = "Des Moines", "Arizona" and "Phoenix"); $s 1= each ($ Capitals);p Rint_r ($s 1);? >

Show Results:

Array ([1] = Columbus [value] = Columbus [0] = = Ohio [key] = Ohio)

Current (), Next (), Prev (), End ()

Mixed current (array Target_array)

The current () function returns the array value at the position of the Target_array array. Unlike the next (), Prev (), and end () functions, current () does not move the pointer.
The next () function returns the array value immediately following the next position in the current array pointer.
The prev () function returns the array value at the previous position of the current pointer, or False if the pointer is in the first position of the array.
The end () function moves the pointer to the last position of the Target_array and returns the last element.

#example7

<?php$fruits= Array ("Apple", "orange", "banana"), $fruit = current ($fruits); Return "Apple" echo $fruit. " <br/> "; $fruit = Next ($fruits); Return "Orange" echo $fruit. " <br/> "; $fruit = prev ($fruits); Return "Apple" echo $fruit. " <br/> "; $fruit = end ($fruits); Return "Banana" echo $fruit. " <br/> ";? >

Show Results:

Apple
Orange
Apple
Banana

=========== below to test the speed of three traversal arrays ===========

In general, there are three ways to traverse an array, for, while, foreach. One of the simplest and most convenient is foreach. Let's test the time spent together traversing a one-dimensional array with 50,000 subscripts.

Test environment:
Intel Core Due2 2GHz
2GB 1067MHz DDR3
Mac OS X 10.5.7
Apache 2.0.59
MySQL 5.0.41
PHP 5.2.6

#example8

<?php$arr= Array (); for ($i = 0; $i < 50000; $i + +) {$arr []= $i *rand (1000,9999);} function GetRuntime () {list ($usec, $sec) =explode ("", Microtime ()), return ((float) $usec + (float) $sec);} ###################################### $time _start= getruntime (); for ($i = 0; $i < count ($arr); $i + +) {$str = $arr [$i];} $time _end= getruntime (); $time _used= $time _end-$time _start;echo ' used time of For: '. Round ($time _used, 7). ' (s) <br/><br/> '; unset ($str, $time _start, $time _end, $time _used); ###################################### $time _start= GetRuntime (), while (List ($key, $val) = each ($arr)) {$str = $val;} $time _end= getruntime (); $time _used= $time _end-$time _start;echo ' used time of while: '. Round ($time _used, 7). ' (s) <br/><br/> '; unset ($str, $key, $val, $time _start, $time _end, $time _used); ############################ ########## $time _start= getruntime (), foreach ($arr as$key=> $val) {$str = $val;} $time _end= getruntime (); $time _used= $time _end-$time _start;echo ' used time of foreach: '. Round ($time _used, 7). ' (s) <br/><br/> ';? >

Test results:

Used time of for:0.0228429 (s)

Used time of while:0.0544658 (s)

Used time of foreach:0.0085628 (s)

After repeated tests, the result shows that for traversing the same array, the foreach speed is the fastest and the slowest is the while. In principle, foreach operates on an array copy (by copying the arrays), while the while is manipulated by moving the internal indicators of the array, which is generally considered to be faster than foreach (since foreach first copies the array in the beginning of execution). While the while moves the internal indicator directly. ), but the result is just the opposite. The reason should be that foreach is an internal implementation of PHP, while the while is a common loop structure. Therefore, foreach is simple and efficient in common applications. Under PHP5, foreach can also traverse the properties of a class.

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.