1. foreach()
foreach()是一个用来遍历数组中数据的最简单有效的方法。
#example1:
复制代码 代码如下:
$colors= array('red','blue','green','yellow');
foreach ($colorsas$color){
echo "Do you like $color?
";
}
?>
2. while()
while() 通常和 list(),each()配合使用。
#example2:
复制代码 代码如下:
$colors= array('red','blue','green','yellow');
while(list($key,$val)= each($colors)) {
echo "Other list of $val.
";
}
?>
3. for()
#example3:
复制代码 代码如下:
$arr= array ("0"=> "zero","1"=> "one","2"=> "two");
for ($i= 0;$i$str= $arr[$i];
echo "the number is $str.
";
}
?>
========= 以下是函数介绍 ==========
key()
mixed key(array input_array)
key()函数返回input_array中位于当前指针位置的键元素。
#example4
复制代码 代码如下:
$capitals= array("Ohio"=> "Columbus","Towa"=> "Des Moines","Arizona"=> "Phoenix");
echo "
Can you name the capitals of these states?
";复制代码 代码如下:
$colors= array('red','blue','green','yellow');
foreach ($colorsas$color){
echo "Do you like $color?
";
}
reset($colors);
while(list($key,$val)= each($colors)) {
echo "$key=> $val
";
}
?>
复制代码 代码如下:
$capitals= array("Ohio"=> "Columbus","Towa"=> "Des Moines","Arizona"=> "Phoenix");
$s1= each($capitals);
print_r($s1);
?>
复制代码 代码如下:
$fruits= array("apple","orange","banana");
$fruit= current($fruits); //return "apple"
echo $fruit."
";
$fruit= next($fruits); //return "orange"
echo $fruit."
";
$fruit= prev($fruits); //return "apple"
echo $fruit."
";
$fruit= end($fruits); //return "banana"
echo $fruit."
";
?>
复制代码 代码如下:
$arr= array();
for($i= 0; $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$str= $arr[$i];
}
$time_end= GetRunTime();
$time_used= $time_end- $time_start;
echo 'Used time of for:'.round($time_used, 7).'(s)
';
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)
';
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)
';
?>