Home > Article > Backend Development > What are the commonly used methods for traversing arrays in PHP?
This article mainly introduces three common methods of traversing arrays in PHP, and analyzes PHP's use of for, foreach, list(), each() and while for arrays in the form of examples. Friends who need to use the related operation skills of traversing arrays can refer to it.
The most manipulated data in PHP is probably the array, which has the characteristics of high efficiency, fast speed and convenient storage.
There are three commonly used methods for traversing arrays in PHP:
1. The for loop is the most flexible in usage. It is so flexible that you doubt your life, but remember the format. very simple.
2. foreach is a function specially provided by PHP for array traversal. It was introduced in the PHP4 version and has the highest execution efficiency.
3. Use list(), each() and while loop in combination to traverse the array. This usage uses Less, but the list() function uses a lot
Instance:
<?php $arr1 = array('http://www.jinsanguo.com/','金三国','PHP教程'); $num = count($arr1);//count()为数组统计函数 for($i=0;$i<$num;++$i){ echo $arr1[$i]."<br/>"; } echo "<hr/>"; $arr2 = array('http://www.jinsanguo.com/','金三国','PHP教程'); foreach($arr2 as $value){ echo $value."<br/>"; } echo "<hr/>"; $arr3 = array('http://www.jinsanguo.com/','金三国','PHP教程'); while(list($key,$value) = each($arr3)){ echo $key.'=>'.$value."<br/>"; } ?>
Run result:
each()
The function needs to pass an array as a parameter, return the key/value pair of the current element in the array, and move 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()
Assign values to a group of variables in one step.
For more related questions, please visit the PHP Chinese website: PHP Video Tutorial
The above is the detailed content of What are the commonly used methods for traversing arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!