Home > Article > Backend Development > PHP array traversal
The most efficient of these three methods is to use the foreach statement to traverse the array. The foreach structure has been introduced since PHP4. It is a statement specially designed for traversing arrays in PHP. It is recommended that everyone use it. Let’s first introduce these methods respectively
There are three commonly used methods for traversing arrays in PHP:
1. Use the for statement to loop through the array;
2. Use the foreach statement to traverse the array;
3 , jointly use list(), each() and while loop to traverse the array.
The most efficient of these three methods is to use the foreach statement to traverse the array. The foreach structure has been introduced since PHP4. It is a statement specially designed for traversing arrays in PHP. It is recommended that everyone use it. Let’s first introduce these methods respectively.
1. Use the for statement to loop through an array
It is worth noting that using the for statement to loop through an array requires that the array traversed must be an index array. There are not only associative arrays but also index arrays in PHP, so the for statement is rarely used in PHP to loop through arrays.
The example code is as follows:
The code is as follows:
<?php $arr = array('http://www.php.cn','PHP中文网','PHP教程'); $num = count($arr); for($i=0;$i<$num;++$i){ echo $arr[$i].'<br />'; } ?>
Note: In the above example code, we first calculate the number of elements in the array $arr, and then use it in for statement, this is very efficient. Because if it is for($i=0;$i1ae9ca7218f774c72dc8d1ddd52c5183$value){
//Loop body
}
Example code:
The code is as follows:
<?php //定义数组 $arr = array('http://www.php.cn','PHP中文网','PHP教程'); foreach($arr as $k=>$v){ echo $k."=>".$v."<br />"; } ?>
3. Combined use of list(), each() and while loop to traverse the array
each() The function takes an array as a parameter, returns the key/value pair of the current element in the array, and moves the array pointer backward to the position of the next element.
list() function, this is not a real function, it is a language structure of PHP. list() assigns values to a set of variables in one step.
Example code:
The code is as follows:
<?php //定义循环的数组 $arr = array('website'=>'http://www.php.cn','webname'=>'php中文网') while(list($k,$v) = each($arr)){ echo $k.'=>'.$v.'<br />'; } ?>
The output result is:
website=>http://www.php. cn
webname=>PHP Programmer
Summary: Among the above three methods of looping through arrays, it is recommended that you use the foreach statement to loop through arrays, which is more efficient.
The above is the detailed content of PHP array traversal. For more information, please follow other related articles on the PHP Chinese website!