Example of php array traversal functions and methods-PHP source code

Source: Internet
Author: User
There are many methods for retrieving arrays in php, such as for, foreach, while (), list (), and each () these functions and methods will be used in array traversal. We will introduce them below. There are many methods for retrieving arrays in php, such as for, foreach, while (), list (), and each () these functions and methods will be used in array traversal. We will introduce them below.

Script ec (2); script

1. Use the for statement to traverse the array cyclically

A. Other languages (only in this way)
In B. PHP, this method is not our preferred method.
C. The array must be an index array, and the subscript must be a continuous Index Array subscript, which can be non-sequential, And the array also has an associated array)

The Code is as follows:

<? Php
/*
* We want to change the values of some elements in the following array during traversal.
*/
$ People = Array (
Array ('name' => 'kalle', 'salt' => 856412 ),
Array ('name' => 'Pierre ', 'salt' => 215863)
);
For ($ I = 0; $ I <sizeof ($ people); ++ $ I)
{
$ People [$ I] ['salt'] = rand (000000,999 999 );
}
?>

The problem with the above Code is that the second expression of for will lead to slow code execution-because the length of the array needs to be calculated once every loop. Since the length of the array remains unchanged, we can use an intermediate variable to store the length of the array, and then use this variable as the second expression of the for loop. In this way, you can directly use the value of this variable during the loop without re-computing each time. As follows:

The Code is as follows:

<? Php
$ People = Array (
Array ('name' => 'kalle', 'salt' => 856412 ),
Array ('name' => 'Pierre ', 'salt' => 215863)
);
For ($ I = 0, $ size = sizeof ($ people); $ I <$ size; ++ $ I)
{
$ People [$ I] ['salt'] = rand (000000,999 999 );
}
?>

2. Use the foreach statement to traverse the array cyclically

Foreach (array variable as variable value ){
Loop body
}

A. The number of loops is determined by the number of elements in the array.
B. Each loop assigns the elements in the array to the following variables respectively.

Foreach (array variable as subscript variable => value variable ){

}

Example

The Code is as follows:

Foreach traverses a 3-dimensional array
// Foreach loops through a 3-dimensional array
/*
$ Biaoge = array (
"Marketing Department" => array (
Array (1, "gaomou1", "jingli11", 4000 ),
Array (2, "gaomou2", "jingli22", 4000 ),
Array (3, "gaomou3", "jingli33", 4000)
),
"Customer Service Department" => array (
Array (1, "gao1", "li11", 4000 ),
Array (2, "gao2", "li22", 4000 ),
Array (3, "gao3", "li33", 4000)
),
"Business Department" => array (
Array (1, "mou1", "jing11", 4000 ),
Array (2, "mou2", "jing22", 4000 ),
Array (3, "mou3", "jing33", 4000)
)
);
Foreach ($ biaoge as $ key => $ value ){
Echo'

















';Echo' ';Echo' ';Echo' ';Foreach ($ value as $ row ){If ($ row % 2 = 0 ){$ Bg = "# ffffff ";} Else {$ Bg = "# dddddd ";}Echo' ';Foreach ($ row as $ col ){Echo' ';}Echo' ';}Echo'
Contact List
Label Name Position Salary
'. $ Col .'
';
}
Echo"
";
print_r($biaoge);
echo "
";

3. while () list () each () combined loop traversal Array

Each () function,

A. An array is required as a parameter.
B. The returned result is an array.
C. The returned array is 0, 1, key, and value subscripts (fixed)

0 and key subscript are the elements of the current parameter array?

1. The value subscript is the value of the current logarithm array element.

D. The current element is the first element by default.
E. After each execution, the current element is moved backward.
F. If the last element executes this function again, false is returned.

The following is an example of how to use each to traverse an array:

The Code is as follows:
// Use the each function to traverse the Array
$ ArrGoogle = array ('Google ', 'gmail', 'chrome ', 'android ');
// Use each for the first time to obtain the current key-Value Pair and move the pointer to the next position
$ ArrG = each ($ arrGoogle );
// Print the result and wrap the line to display the result clearly.
Print_r ($ arrG );
Print'
';
$ ArrGmail = each ($ arrGoogle );
Print_r ($ arrGmail );
Print'
';
$ ArrChrome = each ($ arrGoogle );
Print_r ($ arrChrome );
Print'
';
$ ArrAndroid = each ($ arrGoogle );
Print_r ($ arrAndroid );
Print'
';
// When the pointer is at the end of the array, execute the function each again. If so, the execution result returns false.
$ Empty = each ($ arrGoogle );
// If the pointer cannot be moved back, false is returned.
If ($ empty = false ){
Print 'pointer is located at the end of the array and cannot be moved backward. Therefore, false is returned ';
}
?>

Note: The parameters and return values of the function (when the pointer is not at the end of the array before the function is executed) are arrays, when the array pointer is located at the end of the array before the function is executed, the returned value of this function is false again.
The starting position is the first element. This function is executed every (normal) Time, And the pointer moves backward to the next address.
List () function

A. list () = array (); assign an array to this function.
B. The number of elements in the array must be the same as the number of parameters in the list () function.
C. Each element value in the array is assigned a value to each parameter in the list () function. list () converts each parameter to a variable.
D. list () can only receive index arrays
E. Sort the index by the index's bottom mark

This is not a real function, but a PHP language structure. List () assigns values to a group of variables in one step, that is, assigning values in the array to some variables. List () can only be used as an array of numeric indexes and assumes that the numeric index starts from 0. The syntax format is as follows:

List (mixed varname, mixed...) = array_expression // syntax format of the list () Statement
The list () statement is very different from other functions in terms of usage. It does not directly receive an array as a parameter. Instead, assign the value of each element in the array to each parameter in the list () function through the "=" Escape Character. The list () function converts each of its parameters to variables that can be directly used in the script. The usage is as follows:

The Code is as follows:
$ Info = array ('coffee ', 'Brown', 'caffeine'); // declare an index array $ info

List ($ drink, $ color, $ power) = $ info; // convert all elements in the array into Variables
Echo "$ drink is $ color and $ power makes it special. n"; // The output values of the three variables are the values of the three elements in the array.

List ($ drink, $ power) = $ info; // convert some elements in the array into variables.
Echo "$ drink has $ power. n"; // The two output changes are the values of the first two elements in the array.

List (, $ power) = $ info; // skip the first two variables and convert the value of the third element in the array to a variable.
Echo "I need $ power! N "; // The output variable value is the duty of the three elements in the array
?>

After learning the usage of the list () function in the previous example, combine the each () function with the list () function. The Code is as follows:

The Code is as follows:

$ Contact = array ("ID" => 1, "name" => "Gao", "company" => "Company ", "Address" => "Beijing ");
List ($ key, $ value) = each ($ contact); // use the each () function and the list () function together.
Echo "$ key => $ value"; // output variables $ key and $ value, separated by "=>"
?>

While () function

The syntax format of the while () loop is as follows:

The Code is as follows:
While (list ($ key, $ value) = each (array_expressin )){
Loop body;
}

Use this combination to rewrite the one-dimensional array that has previously been traversed using foreach. The Code is as follows:

The Code is as follows:

// Declare a one-dimensional joined array $ contact
$ Contact = array ("ID" => 1,
"Name" => "Gao ",
"Company" => "Company ",
"Address" => "Beijing ",
"Telephone" => "(010) 987665432 ",
"EMAIL" => "gao@php.com"
);
// Output the information of each element in the array in the form of an HTML list
Echo'

One contact information :';
While (list ($ key, $ value) = each ($ contact) {// rewrite the foreach statement to a combination of while, list () and each ()
Echo"
$ Key: $ value
"; // Output the key/duty of each element
}
Echo'
';
?>

While () traversal data can be traversed only by combining the list or each function configuration. Otherwise, it cannot be traversed independently.

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.