Home> php教程> php手册> body text

php中数组遍历循环实现程序

WBOY
Release: 2016-06-13 10:04:18
Original
1148 people have browsed it

在php中对数组遍历用得最多要算是foreac,while,for这几种方法了,下面我们来介绍这三种遍历数组的实现程序代码吧。

经常会有人问我, PHP的数组, 如果用foreach来访问, 遍历的顺序是固定的么? 以什么顺序遍历呢?
比如:

代码如下 复制代码
$arr['yahoo'] = 2007;
$arr['baidu'] = 2008;
foreach ($arr as $key => $val)
{
//结果是什么?
}

又比如:

代码如下 复制代码

$arr[2] = 'huixinchen';
$arr[1] = 2007;$arr[0] = 2008;
foreach ($arr as $key => $val)
{
//现在结果又是什么?
}

, 当我们使用, each/next系列函数来遍历的时候, 也是通过移动数组的内部指针而实现了顺序遍历, 这里有一个问题, 比如:

代码如下 复制代码

$arr = array(1,2,3,4,5);
foreach ($arr as $v) {//可以获取}
while (list($key, $v) = each($arr))

{//获取不到}
?>

了解到我刚才介绍的知识, 那么这个问题也就很明朗了, 因为foreach会自动reset, 而while这块不会reset, 所以在foreach结束以后, pInternalPointer指向数组最末端, while语句块当然访问不到了, 解决的办法就是在each之前, 先reset数组的内部指针.

也就是说, PHP中遍历数组的顺序, 是和元素的添加先后相关的, 那么, 现在我们就很清楚的知道, 文章开头的问题的输出是:

huixinchen
2007
2008
所以, 如果你想在数字索引的数组中按照索引大小遍历, 那么你就应该使用for, 而不是foreach

代码如下 复制代码
for($i=0,$l=count($arr); $i

{ //这个时候,不能认为是顺序遍历(线性遍历)}

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!