php数组
数组就是一组数据的集合,把一系列数据组织起来,形成一个可操作的整体
一、数组的声明
1 <?php 2 $array = array("asp","php","jsp"); 3 print_r($array);
echo $array[1]; 4 ?>
输出:Array ( [0] => asp [1] => php [2] => jsp ) php
指明键值进行声明:
<?php $array =array ( “1”=>“asp” ,"2" => "php","3" => "jsp" ); print_r($array); ?>
二、数组的类型
数字索引数组 key--->value
关联数组:使用字符串索引来访问存储在数组中的个元素的值,其键值如表所示:
1 <?php 2 $newarray = arrya("firsht"=>1,"second"=>3,"third"=>6); 3 echo $newarry["third"]; 4 ?>
三、数组构造(二维数组)
<?php $array = array("书籍"=>array("chinese","english","math"), "水果"=>array("apple","orange","peach"), "sport"=>array("football","basketball")); print_r($array); ?>
输出:Array ( [书籍] => Array ( [0] => chinese [1] => english [2] => math ) [水果] => Array ( [0] => apple [1] => orange [2] => peach ) [sport] => Array ( [0] => football [1] => basketball ) )
四、遍历数组
4.1 使用foreach()函数遍历数组
1 <?php 2 $array = array("书籍"=>array("chinese","english","math"), 3 "水果"=>array("apple","orange","peach"), 4 "sport"=>array("football","basketball")); 5 foreach($array as $link){ 6 print_r($link); 7 echo "<p>"; 8 } 9 ?>
运行结果:
Array ( [0] => chinese [1] => english [2] => math )
Array ( [0] => apple [1] => orange [2] => peach )
Array ( [0] => football [1] => basketball )
4.2 list()函数遍历数组----日后
五、统计数组元素个数
int count(mixed array,int mode);返回数组元素个数
查询数组中指定元素
array_search()函数在数组中搜索给定的值,找到后返回键名,否则返回false.
mixed array_search(mixed needle ,array haystack,bool strict);
needle指定在数组中搜索的值;haystack指定被搜索的数组;strict为可选参数
六、获取数组中最后一个元素
mixed array_pop(array array);返回数组的最后一个元素,并将数组的长度减1。
七、向数组中添加元素
int array_push(array array,mixed var );var为向数组中添加的元素
八、删除数组中重复的元素
array array_unique(array array);返回删除处理后的数组
1 <?php 2 $array_push =array("hello","hello","pjp"); 3 $result = array_unique($array_push); 4 print_r($result); 5 ?>
输出结果:Array ( [0] => hello [2] => pjp )