<?php
$array = range(0,9);
if(in_array(9,$array)){
echo "数组中存在";
}
?>
运行结果:
数组中存在
实例二:key()取得数组当前的键名:
复制代码 代码如下:
<?php
$array = range(0,9);
$num = rand(0,8);
while($num--)
next($array);
$key = key($array);
echo $key;
?>
此实例结果为动态结果,范围(0-8),不做结果演示。
实例三: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>";
}
echo "</table>";
?>
运行结果:
实例四:array_flip()交换数组的键值和值:
复制代码 代码如下:
<?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 )
实例五:array_keys()、array_values()返回数组中所有的键值和值:
复制代码 代码如下:
<?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()搜索数值:
复制代码 代码如下:
<?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,所以在判断时注意要用"==="
七、数组的排序:
实例一:sort()、rsort()/asort()、arsort()对数组排序:
复制代码 代码如下:
<?PHP
$array = array("b","c","d","a");
sort($array);//从低到高排序
print_r($array);
echo "<br />";
rsort($array);//逆向排序
print_r($array);
?>
结果:
Array ( [0] => a [1] => b [2] => c [3] => d )
Array ( [0] => d [1] => c [2] => b [3] => a )
sort()、rsort()函数对数组进行从低到高的排序,返回结果为bool值;
asort()、arsort()函数是保留键值的排序,排序后键值不重新索引。
实例二:将数组顺序打乱——shuffle()函数:
复制代码 代码如下:
<?PHP
$array = array("a","b","c","d");
shuffle($array);//从低到高排序
print_r($array);
?>
结果为动态结果:
Array ( [0] => c [1] => a [2] => d [3] => b )
shuffle的结果有点随机的意味,每次刷新都不一样。
实例三:array_reverse()数组反向:
复制代码 代码如下:
<?PHP
$array = array("d","b","a","c");
$array = array_reverse($array);//从低到高排序
print_r($array);
?>
运行结果:
Array ( [0] => c [1] => a [2] => b [3] => d )
实例四:自然排序算法——natsort()和natcasesort();
复制代码 代码如下:
<?PHP
$array = array("sort2","Sort5","sort1","sort4");
natsort($array);//从低到高排序
print_r($array);
echo "<br />";
natcasesort($array);
print_r($array);
?>
结果:
Array ( [1] => Sort5 [2] => sort1 [0] => sort2 [3] => sort4 )
Array ( [2] => sort1 [0] => sort2 [3] => sort4 [1] => Sort5 )
natsort()、natcasesort()对数组进行自然排序,就是使用数字的正常排序算法。natcasesort会忽略大小写。
实例五:对数组进行键值排序ksort():
复制代码 代码如下: