PHP 遍历数组的方法汇总
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
- "=> "two");
- ;$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();
- ; $i++){
- );
- }
- function GetRunTime()
- {
- list($usec,$sec)=explode(" ",microtime());
- return ((float)$usec+(float)$sec);
- }
- ######################################
- $time_start= GetRunTime();
- ; $i< count($arr); $i++){
- $str= $arr[$i];
- }
- $time_end= GetRunTime();
- $time_used= $time_end- $time_start;
- ).'(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;
- ).'(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;
- ).'(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 遍历数组的方法汇总的更多相关文章
- php中遍历数组的方法
参考网址:http://www.jb51.net/article/29949.htm 这三种方法中效率最高的是使用foreach语句遍历数组.从PHP4开始就引入了foreach结构,是PHP中专门为 ...
- JaveScript遍历数组的方法
JaveScript遍历数组的方法 第一种:for循环 遍历出数组的每个值 let arr = [1, 2, 3, 4, 5, 6, 7, 8]; for (let i = 0; i < arr ...
- JavaScript数组去重方法汇总
1.运用数组的特性 1.遍历数组,也遍历辅助数组,找出两个数组中是否有相同的项,若有则break,没有的话就push进去. //第一版本数组去重 function unique(arr){ var r ...
- 410 for 循环 运算 改变循环的控制流 死循环 遍历数组 定义方法 有名函数匿名函数 定义函数的方法取值 date math 局部变量 函数 局部与全局变量 次幂/随机数/取绝对值/向上取整/平方根
for(1.表达式1;2.表达式2;3.表达式3){ 4.循环体语句; } 先执行1 ,在执行2, 表达式, 如果2结果为false,退出循环 如果2是true 执行4 在执行3 执行2 举例打印1- ...
- for循环的运算 改变循环的控制流 死循环 遍历数组 定义方法 有名函数匿名函数 定义函数的方法取值 与 自己创建函数取值 局部与全局变量 次幂/随机数/取绝对值/向上取整/平方根
今天学习的是for循环,对for循环的运算有了理解. document.write(" ")里的内容在网页上展示出来 有名函数非常重要!!!!!!!!!!!!!!!!!!!!!并且 ...
- JavaScript 数组(Array)方法汇总
数组(Array)常用方法; 数组常用的方法:concat(),every(), filter(), forEach(), indexOf(), join(), lastIndexOf(), map ...
- ***PHP 遍历数组的方法foreach
foreach http://php.net/manual/zh/control-structures.foreach.php (PHP 4, PHP 5) foreach 语法结构提供了遍历数组的 ...
- 遍历datatable的方法汇总
遍历datatable的方法方法一: DataTable dt = dataSet.Tables[]; ; i < dt.Rows.Count ; i++) { string strName = ...
- js 数组清空 方法 汇总
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...
随机推荐
- iOS--隐藏和显示TabBar的方法
1.隐藏TabBar: - (void)hideTabBar { if (self.tabBarController.tabBar.hidden == YES) { return; } UIView ...
- 每天一个linux命令(11):less 命令
less 工 具也是对文件或其它输出进行分页显示的工具,应该说是linux正统查看文件内容的工具,功能极其强大.less 的用法比起 more 更加的有弹性. 在 more 的时候,我们并没有办法向前 ...
- connection.getResponseCode()!=200
android在网络编程的时候没有执行connection.getResponseCode()!=200 1.用真机测试的时候,电脑必须和手机连同一个局域网. 2.必须开新线程,不放在主线程里面访问. ...
- JPanel设置图片
package com.gr.db; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class We ...
- c++ 中 delete p与 delete []p的区别
#include <cstdio> class A{private: int i;public: ~A() { printf("hi"); }};void d(A *) ...
- 【BZOJ 1901】【Zju 2112】 Dynamic Rankings 动态K值 树状数组套主席树模板题
达神题解传送门:http://blog.csdn.net/dad3zz/article/details/50638360 说一下我对这个模板的理解: 看到这个方法很容易不知所措,因为动态K值需要套树状 ...
- Tomcat+eclipse JSP windows开发环境配置
一.安装Java SE http://www.oracle.com/technetwork/java/javase/downloads/index.html ,配置JAVA_HOME环境变量 二.安装 ...
- 【BZOJ-2818】Gcd 线性筛
2818: Gcd Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 3347 Solved: 1479[Submit][Status][Discuss ...
- poj 2155 Matrix---树状数组套树状数组
二维树状数组模版,唯一困难,看题!!(其实是我英语渣) Matrix Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 22098 ...
- javascript “||”、“&&”的灵活运用
主要介绍了||和 &&的作用 1.|| 和Java中不一样 代表的是 如果左边的true就返回左边 否则返回右边 2.&& 和java中不一样 代表的是 如果左边返回的 ...