_php tutorial for summarizing and analyzing methods of iterating arrays based on PHP

Source: Internet
Author: User
1. foreach ()
foreach () is the simplest and most efficient way to iterate through the data in an array.
#example1:
Copy CodeThe code is as follows:
$colors = Array (' Red ', ' blue ', ' green ', ' yellow ');
foreach ($colorsas $color) {
echo "Do $color?"
";
}
?>

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:
Copy the Code code as follows:
$colors = Array (' Red ', ' blue ', ' green ', ' yellow ');
while (list ($key, $val) = each ($colors)) {
echo "Other list of $val.
";
}
?>

Show Results:
Other list of red.
Other list of blue.
Other list of green.
Other list of yellow.

3. for ()
#example3:
Copy the Code code as follows:
$arr = Array ("0" = "Zero", "1" = "One", "2" = "one");
for ($i = 0; $i < count ($arr); $i + +) {
$str = $arr [$i];
echo "The number is $str.
";
}
?>

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
Copy the Code code as follows:
$capitals = Array ("Ohio" = "Columbus", "towa" = "Des Moines", "Arizona" and "Phoenix");
echo "

Can you name the capitals of these states?

";
while ($key = key ($capitals)) {
echo $key. "
";
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
Copy CodeThe code is as follows:
$colors = Array (' Red ', ' blue ', ' green ', ' yellow ');
foreach ($colorsas $color) {
echo "Do $color?"
";
}
Reset ($colors);
while (list ($key, $val) = each ($colors)) {
echo "$key and $val
";
}
?>

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
Copy CodeThe code is as follows:
$capitals = Array ("Ohio" = "Columbus", "towa" = "Des Moines", "Arizona" and "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 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
Copy CodeThe code is as follows:
$fruits = Array ("Apple", "orange", "banana");
$fruit = current ($fruits); Return "Apple"
echo $fruit. "
";
$fruit = Next ($fruits); Return "Orange"
echo $fruit. "
";
$fruit = prev ($fruits); Return "Apple"
echo $fruit. "
";
$fruit = End ($fruits); Return "Banana"
echo $fruit. "
";
?>

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
Copy CodeThe code is as follows:
$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)

';
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)

';
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)

';
?>

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.

http://www.bkjia.com/PHPjc/327481.html www.bkjia.com true http://www.bkjia.com/PHPjc/327481.html techarticle 1. foreach () foreach () is the simplest and most efficient way to iterate through the data in an array. #example1: Copy the Code as follows: PHP $colors = array (' Red ', ' blue ', ' green ', ' yellow '); F ...

  • 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.