PHP Array Traversal knowledge rollup (including traversal method, array pointer manipulation function, array traversal velocity) _php instance

Source: Internet
Author: User
Tags mixed prev

Introduction to 3 Methods of array traversal

1. foreach ()

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

#example1:

Copy Code code as follows:

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

Show Results:

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

2. while ()

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

#example2:

Copy Code code as follows:

<?php
$colors = Array (' Red ', ' blue ', ' green ', ' yellow ');
while (the 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:

Copy Code code as follows:

<?php
$arr = Array ("0" => "Zero", "1" => "One", "2" => "two");
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 two.

Introduction to the Operation function of array pointer

Key ()

Mixed key (array Input_array)

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

#example4

Copy Code code as follows:

<?php
$capitals = Array ("Ohio" => "Columbus", "Towa" => "Des Moines", "Arizona" => "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 starting position 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 to sort the end.

#example5-Append code to #example1

Copy Code code as follows:

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

Show Results:

Do I like red?
Do you like blue?
Do you like green?
Do I 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 above example if we assign the $colors to another variable within the loop, it will cause an infinite loop.
For example will $s 1 = $colors; Add to the while loop, execute the code again, and the browser will display the results endlessly.

each ()

Array each (array Input_array)

The each () function returns the current key/value pair of the input array and pushes the pointer one position. The returned array contains four keys, the key 0 and key contain the key names, and the key 1 and value contain the corresponding data. Returns False if the previous pointer at the end of the array executes each ().

#example6

Copy Code code as follows:

<?php
$capitals = Array ("Ohio" => "Columbus", "Towa" => "Des Moines", "Arizona" => "Phoenix");
$s 1= each ($capitals);
Print_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 of the current array pointer.
The prev () function returns the array value at the previous position of the current pointer, False if the pointer is already in the first position of the array.
The end () function moves the pointer to the last position in the Target_array and returns the last element.


#example7

Copy Code code as follows:

<?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

Third, test the speed of three kinds of traversal arrays

Generally, there are three ways to traverse an array, for, while, foreach. One of the simplest and most convenient is foreach. Let's take a moment to test how long it takes to traverse 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

Copy Code code as follows:

<?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 the for: '. Round ($time _used, 7). ' (s) <br/><br/> ';
Unset ($str, $time _start, $time _end, $time _used);
######################################
$time _start= getruntime ();
while (the list ($key, $val) = each ($arr)) {
$str = $val;
}
$time _end= getruntime ();
$time _used= $time _end-$time _start;
Echo ' Used time of: '. 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)

The

has been tested repeatedly, and the result shows that foreach is the fastest and slowest while traversing the same array. In principle, foreach operates on an array copy (by copying the arrays) while the while is manipulated by moving the internal index of the array, which is generally logically considered to be faster than foreach (because foreach first copies the array when it starts executing). While the while directly moving internal indicators. ), but the result is just the opposite. The reason for this is that foreach is the internal implementation of PHP while the while is the universal loop structure. So, in a common application, foreach is simple and highly efficient. Under PHP5, foreach can also traverse the properties of a class.

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.