基于基于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
$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)) {