The most commonly used methods for array traversal in PHP are forac, while, and for. Let’s introduce the implementation codes of these three array traversals.
People often ask me, if a PHP array is accessed using foreach, is the order of traversal fixed? In what order should it be traversed?
For example:
The code is as follows
代码如下 |
复制代码 |
$arr['yahoo'] = 2007;
$arr['baidu'] = 2008;
foreach ($arr as $key => $val)
{
//结果是什么?
}
|
|
Copy code
|
|
代码如下 |
复制代码 |
$arr[2] = 'huixinchen';
$arr[1] = 2007;$arr[0] = 2008;
foreach ($arr as $key => $val)
{
//现在结果又是什么?
}
|
$arr['yahoo'] = 2007;
$arr['baidu'] = 2008;
foreach ($arr as $key => $val)
{
//What is the result?
}
代码如下 |
复制代码 |
$arr = array(1,2,3,4,5);
foreach ($arr as $v) {//可以获取}
while (list($key, $v) = each($arr))
{//获取不到}
?>
|
Another example:
The code is as follows
|
Copy code
|
|
代码如下 |
复制代码 |
for($i=0,$l=count($arr); $i
|
$arr[2] = 'huixinchen';
$arr[1] = 2007;$arr[0] = 2008;
foreach ($arr as $key => $val)
{
//What is the result now?
}
, when we use the each/next series of functions to traverse, we also achieve sequential traversal by moving the internal pointer of the array. There is a problem here, such as:
The code is as follows
|
Copy code
$arr = array(1,2,3,4,5);
foreach ($arr as $v) {//can be obtained}
while (list($key, $v) = each($arr))
{//Cannot obtain}
?>
After understanding the knowledge I just introduced, this problem will be very clear, because foreach will automatically reset, but the while block will not reset, so after the foreach ends, pInternalPointer points to the end of the array, and of course the while statement block It is no longer accessible. The solution is to reset the internal pointer of the array before each.
In other words, the order in which arrays are traversed in PHP is related to the order in which elements are added. So, now we clearly know that the output of the question at the beginning of the article is:
huixinchen
2007
2008
So, if you want to iterate through a numerically indexed array according to the index size, then you should use for, not foreach
The code is as follows
|
Copy code
|
for($i=0,$l= count($arr); $i
{ //At this time, it cannot be considered as sequential traversal (linear traversal)}
http://www.bkjia.com/PHPjc/631283.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631283.htmlTechArticleThe most commonly used methods for array traversal in PHP are forac, while, and for. Below we Let’s introduce the implementation codes of these three array traversals. People often ask me, the number of PHP...
|
|
|