关于PHP数组相关的常用函数
PHP是一种非常强大的编程语言,其中的数组函数是开发中经常用到的。下面列出了一些PHP中关于数组的常用函数以及相应的示例代码:
- array_push() - 将一个或多个元素压入数组的末尾
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
输出:
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
- array_pop() - 删除并返回数组的最后一个元素
$stack = array("orange", "banana", "apple");
$fruit = array_pop($stack);
print_r($stack);
echo $fruit;
输出:
Array
(
[0] => orange
[1] => banana
)
apple
- array_shift() - 删除并返回数组的第一个元素
$queue = array("orange", "banana", "apple");
$fruit = array_shift($queue);
print_r($queue);
echo $fruit;
输出:
Array
(
[0] => banana
[1] => apple
)
orange
- array_unshift() - 在数组开头插入一个或多个元素
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
输出:
Array
(
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)
- array_merge() - 合并一个或多个数组
$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
)
- array_reverse() - 返回一个元素顺序颠倒的数组
$input = array("php", 4.0, "green", "red");
$reversed = array_reverse($input);
print_r($reversed);
输出:
Array
(
[0] => red
[1] => green
[2] => 4
[3] => php
)
- array_keys() - 返回数组中所有的键名
$array = array("blue" => "sky", "green" => "grass", "red" => "apple");
print_r(array_keys($array));
输出:
Array
(
[0] => blue
[1] => green
[2] => red
)
- array_values() - 返回数组中所有的值
$array = array("blue" => "sky", "green" => "grass", "red" => "apple");
print_r(array_values($array));
输出:
Array
(
[0] => sky
[1] => grass
[2] => apple
)
- count() - 返回数组中的元素数目
$array = array("orange", "banana", "apple");
echo count($array);
输出:
3
- in_array() - 检查一个值是否存在于数组中
$fruits = array("orange", "banana", "apple");
if (in_array("apple", $fruits)) {
echo "Got apple!";
}
输出:
Got apple!
以上是一些常见的PHP数组函数的示例代码。
此处评论已关闭