php数组实例之数组键值和值操作

发布时间:2020-01-24编辑:脚本学堂
本文介绍下,有关php数组的键值,以及php数组键值操作的相关内容,有需要的朋友参考下。

以下是php数组键值操作的一些例子,分享下。

例1,in_array()检测数组中是否有某个值存在:

<?php
$array = range(0,9);
if(in_array(9,$array)){
echo "数组中存在";
} //by www.jb200.com
?>

运行结果:数组中存在

例2,key()取得数组当前的键名:

<?php
$array = range(0,9);
$num = rand(0,8);
while($num--)
next($array);
$key = key($array);
echo $key;
//by www.jb200.com
?>

此实例结果为动态结果,范围(0-8),不做结果演示。

例3,list()函数把数组中的值赋给指定变量:

<?PHP
$staff = array(
array("姓名","性别","年龄"),
array("小张","男",24),
array("小王","女",25),
array("小李","男",23)
);
echo "<table border=2>";
while(list($keys,$value) = each($staff)){
list($name,$sex,$age) = $value;
echo "<tr><td>$name</td><td>$sex</td><td>$age</td></tr>";
} //by www.jb200.com
echo "</table>";
?>

例4,array_flip()交换数组的键值和值:
1)、

<?PHP
$array = array("red","blue","yellow","Black");
print_r($array);
echo "<br />";
$array = array_flip($array);
print_r($array);
?>

运行结果:
Array ( [0] => red [1] => blue [2] => yellow [3] => Black )
Array ( [red] => 0 [blue] => 1 [yellow] => 2 [Black] => 3 )

2)、

<?PHP
$array = array("red","blue","yellow","Black");
$result = array_keys($array);
print_r($result);
echo "<br />";
$result = array_values($array);
print_r($result);
?>

运行结果:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
Array ( [0] => red [1] => blue [2] => yellow [3] => Black )
实例六:array_search()搜索数值:

3)、

<?PHP
$array = array("red","blue","yellow","Black");
$result = array_search("red",$array);
if(($result === NULL)){
echo "不存在数值red";
}else{
echo "存在数值 $result";
}
?>

结果:存在数值 0
函数array_search()返回的值可能为false或0或NULL,所以在判断时注意要用"==="