The article simply uses foreach for list each while to traverse arrays, including common one-dimensional arrays and two-dimensional array traversal methods. The following describes in detail how to use each function.
*/
$ Foreach = array (1, 2, 3 );
$ Array2 = array ('a' => 33, 'BB '=> 22, 'www .111cn.net' => 11), array ('DD' => 44, 'ee '=> 55, 'FF' => 66 ));
// Use for foreach to traverse one-dimensional data
For ($ I = 0; $ I <count ($ foreach); $ I ++)
{
Echo 'foreach ['. $ I.'] = '. $ foreach [$ I].' <br> ';
}
/*
Foreach [0] = 1
Foreach [1] = 2
Foreach [2] = 3
Then we can use foreach to traverse
*/
Foreach ($ foreach as $ v)
{
Echo 'foreach = '. $ v.' <br> ';
}
/*
Foreach = 1
Foreach = 2
Foreach = 3
The above uses to traverse one-dimensional data. Let's look at the two-dimensional array.
*/
Foreach ($ array2 as $ key => $ value)
{
Foreach ($ value as $ k => $ v)
{
Echo '$ arr ['. $ key. '] ['. $ k. '] ='. $ v;
}
Echo "<br> ";
}
/* // Check list each.
The each () function generates an array consisting of the key and key values of the elements pointed to by the current internal pointer of the array, and moves the internal pointer forward.
The returned array contains four elements: key name 0, 1, key, and value. Unit 0 and key contain the key name of the array unit, and 1 and value contain data.
If the internal pointer is out of the array range, this function returns false.
Syntax
Each (array) parameter description
Array is required. Specifies the array to be used.
List function
The list () function assigns values to a group of variables with elements in the array.
Note that, like array (), list () is actually a language structure, not a function.
Syntax
List (var1, var2. ..) parameter description
Var1 is required. The first variable to be assigned a value.
Var2 is optional. There can be multiple variables.
Tips and comments
Note: This function is only used for numeric index arrays. It is assumed that the numeric index starts from 0.
*/
$ Colors = array ('red', 'blue', 'green', 'yellow ');
While (list ($ key, $ val) = each ($ colors )){
Echo "other list of $ val. <br/> ";
}
/*
Other list of red.
Other list of blue.
Other list of green.
Other list of yellow.
For statement
If you have determined the number of times the code block is repeated, you can use the for statement.
Syntax
For (initialization; condition; increment)
{
Code to be executed;
}
Note: the for statement has three parameters. The first parameter initializes the variable, the second parameter saves the condition, and the third parameter contains the increment required for the execution cycle. If the initialization or increment parameter contains multiple variables, separate them with commas. The condition must be calculated as true or false.
The foreach statement is used to traverse arrays cyclically.
Each cycle is performed, the value of the current array element is assigned to the value variable (the array pointer is moved one by one)-and so on
*/