PHP数组遍历知识汇总(包含遍历方法、数组指针操作函数、数组遍历测速)


Posted in PHP onJuly 05, 2014

一、数组遍历的3个方法介绍

1. foreach()

foreach()是一个用来遍历数组中数据的最简单有效的方法。

#example1:

<?php

$colors= array('red','blue','green','yellow');

foreach ($colorsas$color){

echo "Do you like $color? <br />";

}

?>

显示结果:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

2. while()

while() 通常和 list(),each()配合使用。

#example2:

<?php

$colors= array('red','blue','green','yellow');

while(list($key,$val)= each($colors)) {

echo "Other list of $val.<br />";

}

?>

显示结果:

Other list of red.
Other list of blue.
Other list of green.
Other list of yellow.

3. for()

#example3:

<?php

$arr= array ("0"=> "zero","1"=> "one","2"=> "two");

for ($i= 0;$i< count($arr); $i++){

$str= $arr[$i];

echo "the number is $str.<br />";

}

?>

显示结果:

the number is zero.
the number is one.
the number is two.

二、数组指针操作函数介绍

key()

mixed key(array input_array)

key()函数返回input_array中位于当前指针位置的键元素。

#example4

<?php

$capitals= array("Ohio"=> "Columbus","Towa"=> "Des Moines","Arizona"=> "Phoenix");

echo "<p>Can you name the capitals of these states?</p>";

while($key= key($capitals)) {

echo $key."<br />";

next($capitals);

//每个key()调用不会推进指针。为此要使用next()函数

}

?>

显示结果:

Can you name the capitals of these states?
Ohio
Towa
Arizona

reset()

mixed reset(array input_array)

reset()函数用来将input_array的指针设置回数组的开始位置。如果需要在一个脚本中多次查看或处理同一个数组,就经常使用这个函数,另外这个函数还常用于排序结束时。

#example5 - 在#example1上追加代码

<?php

$colors= array('red','blue','green','yellow');

foreach ($colorsas$color){

echo "Do you like $color? <br />";

}

reset($colors);

while(list($key,$val)= each($colors)) {

echo "$key=> $val<br />";

}

?>

显示结果:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
0 => red
1 => blue
2 => green
3 => yellow

注意:将一个数组赋值给另一个数组时会重置原来的数组指针,因此在上例中如果我们在循环内部将 $colors 赋给了另一个变量的话将会导致无限循环。
例如将 $s1 = $colors; 添加到while循环内,再次执行代码,浏览器就会无休止地显示结果。

each()

array each(array input_array)

each()函数返回输入数组当前键/值对,并将指针推进一个位置。返回的数组包含四个键,键0和key包含键名,而键1和value包含相应的数据。如果执行each()前指针位于数组末尾,则返回FALSE。

#example6

<?php

$capitals= array("Ohio"=> "Columbus","Towa"=> "Des Moines","Arizona"=> "Phoenix");

$s1= each($capitals);

print_r($s1);

?>

显示结果:

Array ( [1] => Columbus [value] => Columbus [0] => Ohio [key] => Ohio )

current(),next(),prev(),end()

mixed current(array target_array)

current()函数返回位于target_array数组当前指针位置的数组值。与next()、prev()、和end()函数不同,current()不移动指针。
next()函数返回紧接着放在当前数组指针的下一个位置的数组值。
prev()函数返回位于当前指针的前一个位置的数组值,如果指针本来就位于数组的第一个位置,则返回FALSE。
end()函数将指针移向target_array的最后一个位置,并返回最后一个元素。

#example7

<?php

$fruits= array("apple","orange","banana");

$fruit= current($fruits); //return "apple"

echo $fruit."<br />";

$fruit= next($fruits); //return "orange"

echo $fruit."<br />";

$fruit= prev($fruits); //return "apple"

echo $fruit."<br />";

$fruit= end($fruits); //return "banana"

echo $fruit."<br />";

?>

显示结果:

apple
orange
apple
banana

三、测试三种遍历数组的速度

一般情况下,遍历一个数组有三种方法,for、while、foreach。其中最简单方便的是foreach。下面先让我们来测试一下共同遍历一个有50000个下标的一维数组所耗的时间。

测试环境:
Intel Core Due2 2GHz
2GB 1067MHz DDR3
Mac OS X 10.5.7
Apache 2.0.59
MySQL 5.0.41
PHP 5.2.6

#example8

<?php

$arr= array();

for($i= 0; $i< 50000; $i++){

$arr[]= $i*rand(1000,9999);

}

function GetRunTime()

{

list($usec,$sec)=explode(" ",microtime());

return ((float)$usec+(float)$sec);

}

######################################

$time_start= GetRunTime();

for($i= 0; $i< count($arr); $i++){

$str= $arr[$i];

}

$time_end= GetRunTime();

$time_used= $time_end- $time_start;

echo 'Used time of for:'.round($time_used, 7).'(s)<br /><br />';

unset($str, $time_start, $time_end, $time_used);

######################################

$time_start= GetRunTime();

while(list($key, $val)= each($arr)){

$str= $val;

}

$time_end= GetRunTime();

$time_used= $time_end- $time_start;

echo 'Used time of while:'.round($time_used, 7).'(s)<br /><br />';

unset($str, $key, $val, $time_start, $time_end, $time_used);

######################################

$time_start= GetRunTime();

foreach($arr as$key=> $val){

$str= $val;

}

$time_end= GetRunTime();

$time_used= $time_end- $time_start;

echo 'Used time of foreach:'.round($time_used, 7).'(s)<br /><br />';

?>

测试结果:

Used time of for:0.0228429(s)

Used time of while:0.0544658(s)

Used time of foreach:0.0085628(s)

经过反复多次测试,结果表明,对于遍历同样一个数组,foreach速度最快,最慢的则是while。从原理上来看,foreach是对数组副本进行操作(通过拷贝数组),而while则通过移动数组内部指标进行操作,一般逻辑下认为,while应该比foreach快(因为foreach在开始执行的时候首先把数组复制进去,而while直接移动内部指标。),但结果刚刚相反。原因应该是,foreach是PHP内部实现,而while是通用的循环结构。所以,在通常应用中foreach简单,而且效率高。在PHP5下,foreach还可以遍历类的属性。

PHP 相关文章推荐
提问的智慧(2)
Oct 09 PHP
php生成EXCEL的东东
Oct 09 PHP
php中json_encode中文编码问题分析
Sep 13 PHP
php操作XML、读取数据和写入数据的实现代码
Aug 15 PHP
PHP中使用hidef扩展代替define提高性能
Apr 09 PHP
PHP的PDO操作简单示例
Mar 30 PHP
PHP中仿制 ecshop验证码实例
Jan 06 PHP
Yii2框架实现登录、退出及自动登录功能的方法详解
Oct 24 PHP
Laravel Intervention/image图片处理扩展包的安装、使用与可能遇到的坑详解
Nov 14 PHP
php app支付宝回调(异步通知)详解
Jul 25 PHP
tp5(thinkPHP5框架)时间查询操作实例分析
May 29 PHP
PHP中通过getopt解析GNU C风格命令行选项
Nov 18 PHP
php遍历数组的4种方法总结
Jul 05 #PHP
CodeIgniter实现更改view文件夹路径的方法
Jul 04 #PHP
PHP关于htmlspecialchars、strip_tags、addslashes的解释
Jul 04 #PHP
php socket客户端及服务器端应用实例
Jul 04 #PHP
PHP使用range协议实现输出文件断点续传代码实例
Jul 04 #PHP
PHP实现对文本数据库的常用操作方法实例演示
Jul 04 #PHP
成为好程序员必须避免的5个坏习惯
Jul 04 #PHP
You might like
php array_intersect比array_diff快(附详细的使用说明)
2011/07/03 PHP
使用YUI+Ant 实现JS CSS压缩
2014/09/02 PHP
标准版Eclipse搭建PHP环境的详细步骤
2015/11/18 PHP
10个对初学者非常有用的PHP技巧
2016/04/06 PHP
php 数据结构之链表队列
2017/10/17 PHP
thinkphp中U方法按路由规则生成url的方法
2018/03/12 PHP
PHP的PDO预定义常量讲解
2019/01/24 PHP
thinkPHP和onethink微信支付插件分享
2019/08/11 PHP
Yii框架的路由配置方法分析
2019/09/09 PHP
laravel框架中视图的基本使用方法分析
2019/11/23 PHP
PHP变量的作用范围实例讲解
2020/12/22 PHP
jQuery.autocomplete 支持中文输入(firefox)修正方法
2011/03/10 Javascript
jQuery的缓存机制浅析
2014/06/07 Javascript
JQuery Tips相关(1)----关于$.Ready()
2014/08/14 Javascript
基于jQuery实现多层次的手风琴效果附源码
2015/09/21 Javascript
JavaScript通过代码调用Flash显示的方法
2016/02/02 Javascript
JavaScript编程设计模式之观察者模式(Observer Pattern)实例详解
2017/10/25 Javascript
webpack v4 从dev到prd的方法
2018/04/02 Javascript
ES6 Map结构的应用实例分析
2019/06/26 Javascript
基于JS抓取某高校附近共享单车位置 使用web方式展示位置变化代码实例
2019/08/27 Javascript
[46:10]2014 DOTA2国际邀请赛中国区预选赛 CnB VS HGT
2014/05/21 DOTA
基于python实现蓝牙通信代码实例
2019/11/19 Python
Python爬虫解析网页的4种方式实例及原理解析
2019/12/30 Python
PyCharm取消波浪线、下划线和中划线的实现
2020/03/03 Python
Spy++的使用方法及下载教程
2021/01/29 Python
美国在线宠物用品商店:Entirely Pets
2017/01/01 全球购物
Draper James官网:知名演员瑞茜·威瑟斯彭所创品牌
2017/10/25 全球购物
香港百佳网上超级市场:PARKNSHOP.com
2020/06/10 全球购物
成都思必达公司C#程序员招聘面试题
2013/06/26 面试题
软件测试笔试题
2012/10/25 面试题
25道Java面试题集合
2013/05/21 面试题
给老婆的保证书范文
2014/04/28 职场文书
大学生实习证明
2015/06/16 职场文书
2016个人廉洁自律承诺书
2016/03/25 职场文书
设置IIS Express并发数
2022/07/07 Servers
Linux中一对多配置日志服务器的详细步骤
2022/07/23 Servers