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和html' target='_blank'>value包含相应的数据。如果执行each()前指针位于数组末尾,则返回FALSE。 #example6 复制代码 代码如下: ?php $capitals= array("Ohio"= "Columbus","Towa"= "Des Moines","Arizona"= "Phoenix"); $s1= each($capitals); print_r($s1); ?
测试结果: 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教程