数组
PHP数组是一个有序映射(包含基于键的值)。 它用于在单个变量中保存相似类型的多个值。
索引数组
默认情况下,所有PHP数组都会被分配索引号。
定义索引数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?php
$season=array("summer","winter","spring","autumn");
$season=array(0=>"summer",1=>"winter",2=>"spring",3=>"autumn");
$season[0]="summer"; $season[1]="winter"; $season[2]="spring"; $season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]"; ?>
|
关联数组
使用=>符号将名称与PHP中的每个数组元素的值相关联。
定义关联数组
1 2 3 4 5 6 7 8 9 10 11 12 13
| <?php
$seasons=array("season1"=>"summer","season2"=>"winter","season3"=>"spring","season4"=>"autumn");
$season["season1"]="summer"; $season["season2"]="winter"; $season["season3"]="spring"; $season["season4"]="autumn";
echo "Season are: $seasons["season1"]"; ?>
|
多维数组
多维数组是包含一个或多个数组的数组。
示例
1 2 3 4 5 6 7 8 9
| <?php
$cars = array ( array("Volvo",100,96), array("BMW",60,59), array("Toyota",110,100) ); ?>
|
数组函数
PHP提供了各种数组函数来访问和操作数组的元素。
array函数
array()函数创建并返回一个数组。
1
| $season=array("summer","winter","spring","autumn");
|
count函数
count()函数计算数组中的所有元素的数量。
1 2 3 4
| <?php $season=array("summer","winter","spring","autumn"); echo count($season); ?>
|
sort函数
sort()函数排序数组中的所有元素
1 2 3 4 5 6 7
| <?php $season=array("summer","winter","spring","autumn"); sort($season); foreach( $season as $s ) { echo "$s"; }
|
array_search函数
array_search()函数搜索数组中的指定值。 如果搜索成功,则返回键。
1 2 3 4 5
| <?php $season=array("summer","winter","spring","autumn"); $key=array_search("spring",$season); echo $key; ?>
|
array_intersect函数
array_intersect()函数返回两个数组的交集。
1 2 3 4 5 6 7 8 9
| <?php $name1=array("maxsu","john","vivek","minsu"); $name2=array("umesh","maxsu","kartik","minsu"); $name3=array_intersect($name1,$name2); foreach( $name3 as $n ) { echo "$n<br />"; } ?>
|
array_merge函数
array_merge()函数合并一个或多个数组,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <?php $array1 = array("color" => "red", 2, 4); $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4); $result = array_merge($array1, $array2); print_r($result); ?>
Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )
|