<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <?php //数组定义 //跟java定义方式不同,数组里面可以放任何类型的数据 $attr = array(1,2,3,4,"aa");//索引数组 print_r($attr); //关联数组的定义 $attr =array("one"=>10,"2"=>"aa","three"=>20); print_r($attr); echo $attr[one]; //数组遍历 //for 循环遍历,针对于索引数组,不能遍历关联数组 $attr = array(1,2,3,4,"aa"); for($i=0;$i<count($attr);$i++) { echo $attr[$i]."<br>"; } //foreach遍历.可以遍历索引数组和关联数组 $attr =array("one"=>10,"2"=>"aa","three"=>20); foreach($attr as $value) //只取value { echo $value."<br>"; } foreach($attr as $key=>$value) //取key 和value 两种都取 { echo $key ."=>".$value."<br>"; } //each()函数,取数组里面的第一个元素,依次向下取值,然后将该元素以数组的形式返回 $attr =array("one"=>10,"2"=>"aa","three"=>20); print_r (each($attr)); echo"<br>"; print_r (each($attr)); echo"<br>"; print_r (each($attr)); echo "-----------------------"."<br>"; //将指针复位,指向第一个元素 reset($attr); print_r (each($attr)); echo"<br>"; print_r (each($attr)); echo"<br>"; print_r (each($attr)); //list()函数 //如果只想取最后一个,前面的写成空,不能不写(就是逗号必须有) $attr = array(1,2,3,4,"aa"); //$attr =array("one"=>10,"2"=>"aa","three"=>20); 关联数组 第一个第三个没有索引,所以显示不出来 list($a,$b,$c,$d,$e)= $attr; //左边写变量,他会将右边的数组里的数依次赋给左边的变量 echo $a; echo $b; echo $c; echo $d; echo $e; //用each()和list()函数遍历数组 $attr =array("one"=>10,"2"=>"aa","three"=>20); list($key,$value) =each ($attr); echo $key."=>".$value; list($key,$value) =each ($attr); echo $key."=>".$value; //遍历 $attr =array("one"=>10,"2"=>"aa","three"=>20); while(list($key,$value)= each ($attr)) { echo $key."=>".$value."<br>"; } //指针 $attr =array("one"=>10,"2"=>"aa","three"=>20); echo current($attr); //取当前指针直线的内容value echo key($attr); //取当前指针指向的索引key echo "<br />"; next($attr); //将指针向下移动 echo current($attr); echo key($attr); echo"<br />"; prev($attr); //将指针向上移动 echo current($attr); echo key($attr); echo"<br>"; end($attr); //将指针指向最后一个元素 echo current($attr); echo key($attr); echo"<br />"; reset($attr); //将指针复位 echo current($attr); echo key($attr); echo "<br />"; //用指针遍历 $attr =array("one"=>10,"2"=>"aa","three"=>20); do { echo key($attr); echo current($attr); echo "<br />"; } while(next($attr)); ?> </body> </html>