There are many functions that can be used to traverse arrays in PHP. For example, there are four functions: for statement, list, each, and foreach. These are also the main functions for traversing arrays in PHP. Let me give them below. Introduce everyone.
foreach traverses the array
When we use arrays, we often need to traverse the array and obtain each key or element value. PHP provides some functions specifically for traversing arrays. Here we first introduce the usage of foreach array traversal function.
Structural form:
foreach (array_expression as $value) statement
/*array_expression is the array to be traversed
The function of as is to assign the value of the array to $value
Statement is the subsequent statement
*/
Example 1:
The code is as follows | Copy code | ||||||||
'black' => 'black' , 'red' => 'red' ,
'green' => 'green', ";
|
foreach ( array_expression as $key => $value ) statement
The code is as follows | Copy code | ||||
foreach( $color as $c) echo $c ."
"; |
The code is as follows | Copy code |
$languages=array(1=>"php",
5=>"html",
10=>"css");
$a=each($languages); /* First traversal of array */
echo $a[0] ."t";
echo $a[1] ." "; $a=each($languages); /* Traverse the array for the second time */ echo $a[key] ."t"; echo $a[value]; ?> |
list traverses array
The function list can be assigned to variables once when traversing the array, and is usually used in conjunction with the each() function. Using the list() function makes it easier to access the keys and values returned by each().
Example:
代码如下 | 复制代码 |
$date=array(1=>"Monday", 2=>"Tuesday", 3=>"Wednesday"); list($key,$value)=each($date); /* 遍历函数 */ echo "$key $value" ." "; /* 输出第一个数组 */ $next=next($date); /* 指针后移 */ echo "$next"; ?> |
ps: The list() function is just the opposite of the array() function. array() constructs a series of data into an array, while list() splits the array into data.
for traverses the array
In addition to some of the predefined array traversal functions in PHP, we can also use the loop feature of the for statement to traverse the array and output it. Examples are given below:
The code is as follows
|
Copy code | ||||