PHP几个数组函数
array_intersect比较两个数组的键值,并返回交集:
<?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"green","g"=>"blue"); $result=array_intersect($a1,$a2); print_r($result); ?>
Array ( [a] => red [b] => green [c] => blue )
array_unique移除数组中重复的值
<?php $a=array("a"=>"red","b"=>"green","c"=>"red"); print_r(array_unique($a)); ?>
Array ( [a] => red [b] => green )
array_map 将函数作用到数组的每一个值上,并返回作用后的新数组
<?php function myfunction($v) { return($v*$v); } $a=array(1,2,3,4,5); print_r(array_map("myfunction",$a)); ?>
Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
array_key_exists() 函数检查某个数组中是否存在指定的键名,如果键名存在则返回 true,如果键名不存在则返回 false。
<?php $a=array("Volvo"=>"XC90","BMW"=>"X5"); if (array_key_exists("Volvo",$a)) { echo "键存在!"; } else { echo "键不存在!"; } ?>
键存在!
array_merge()合并两个或者多个数组
<?php $a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_merge($a1,$a2)); ?>
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
array_push() 函数向第一个参数的数组尾部添加一个或多个元素(入栈),然后返回新数组的长度。
<?php $a=array("red","green"); array_push($a,"blue","yellow"); print_r($a); ?>
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
array_pop() 函数删除数组中的最后一个元素。
<?php $a=array("red","green","blue"); array_pop($a); print_r($a); ?>
Array ( [0] => red [1] => green )
array_chunk() 函数把数组分割为新的数组块。
<!DOCTYPE html> <html> <body> <?php $age=array("Bill"=>"60","Steve"=>"56","Mark"=>"31","David"=>"35");//true代表保留原来的键 print_r(array_chunk($age,2,true)); ?> </body> </html>
array_reverse() 函数返回翻转顺序的数组
<?php $a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota"); print_r(array_reverse($a,true));//默认为true,为false时不保留键名 ?>
Array ( [c] => Toyota [b] => BMW [a] => Volvo )
shuffle() 函数把数组中的元素按随机顺序重新排列