PHP array traversal Knowledge Summary (including traversal method, array pointer operation function, array traversal speed) _ PHP Tutorial

Source: Internet
Author: User
PHP array traversal Knowledge Summary (including the traversal method, array pointer operation function, array traversal speed ). I. INTRODUCTION to three methods of array traversal 1. foreach () is the simplest and most effective method to traverse data in an array. # Example1: Copy the code as follows: php $ colorsar I. INTRODUCTION to three methods of array traversal

1. foreach ()

Foreach () is the simplest and most effective way to traverse data in an array.

# Example1:

The code is as follows:


<? Php
$ Colors = array ('red', 'blue', 'green', 'yellow ');
Foreach ($ colorsas $ color ){
Echo "Do you like $ color?
";
}
?>


Display result:

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

2. while ()

While () is usually used with list () and each.

# Example2:

The code is as follows:


<? Php
$ Colors = array ('red', 'blue', 'green', 'yellow ');
While (list ($ key, $ val) = each ($ colors )){
Echo "Other list of $ val.
";
}
?>


Display result:

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

3. ()

# Example3:

The code is 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.
";
}
?>


Display result:

The number is zero.
The number is one.
The number is two.

II. Introduction to array pointer operation functions

Key ()

Mixed key (array input_array)

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

# Example4

The code is as follows:


<? Php
$ Capitals = array ("Ohio" => "Columbus", "Towa" => "Des Moines", "Arizona" => "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. Use the next () function.
}
?>

Display result:

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. If you need to view or process the same array multiple times in a script, this function is often used. In addition, this function is often used at the end of sorting.

# Example5-append Code on # example1

The code is as follows:


<? Php
$ Colors = array ('red', 'blue', 'green', 'yellow ');
Foreach ($ colorsas $ color ){
Echo "Do you like $ color?
";
}
Reset ($ colors );
While (list ($ key, $ val) = each ($ colors )){
Echo "$ key => $ val
";
}
?>

Display result:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
0 => red
1 => blue
2 => green
3 => yellow

Note: When an array is assigned to another array, the original array pointer is reset, therefore, in the above example, if $ colors is assigned to another variable within the loop, it will lead to an infinite loop.
For example, add $ s1 = $ colors; to the while loop and execute the code again, 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 to a position. The returned array contains four keys. Keys 0 and key contain the key name, while Keys 1 and value contain the corresponding data. If the pointer before execution of each () is located at the end of the array, FALSE is returned.

# Example6

The code is as follows:


<? Php
$ Capitals = array ("Ohio" => "Columbus", "Towa" => "Des Moines", "Arizona" => "Phoenix ");
$ S1 = each ($ capitals );
Print_r ($ s1 );
?>

Display result:

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 current pointer 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 that is placed next to the current array pointer.
The prev () function returns the array value located at the first position of the current pointer. if the pointer is located at the first position of the array, FALSE is returned.
The end () function moves the pointer to the last position of target_array and returns the last element.


# Example7

The code is as follows:


<? Php
$ 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 ."
";
?>


Display result:

Apple
Orange
Apple
Banana

3. test the speed of the three traversal arrays

Generally, there are three methods to traverse an array: for, while, and foreach. Among them, the easiest and most convenient is foreach. Next, let's test the time it takes to traverse a one-dimensional array with 50000 subtopics.

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


# Example8

The code is as follows:


<? Php
$ Arr = array ();
For ($ I = 0; I 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 results show that for traversing the same array, foreach is the fastest, while is the slowest. In principle, foreach operates on the array copy (by copying the array), while moves the internal indicator of the array, while should be faster than foreach (because foreach first copies the array when starting execution, while directly moves the internal indicator .), But the result is just the opposite. The reason should be that foreach is implemented inside PHP, while is a general loop structure. Therefore, foreach is simple and efficient in common applications. In PHP5, foreach can also traverse class attributes.

Partition 1. foreach () is the simplest and most effective method for traversing data in an array. # Example1: the code is as follows: php $ colors = ar...

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.