欢迎访问宙启技术站
智能推送

10个常用的php数组函数及使用案例

发布时间:2023-10-30 15:19:08

1. array_push(): 将一个或多个元素插入到数组的末尾

案例:

$fruits = array("apple", "banana");
array_push($fruits, "orange", "grape");
print_r($fruits);

输出结果:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)

2. array_pop(): 删除数组中的最后一个元素

案例:

$fruits = array("apple", "banana", "orange");
$lastFruit = array_pop($fruits);
echo $lastFruit;

输出结果:

orange

3. array_shift(): 删除数组中的 个元素,并返回被删除的元素

案例:

$fruits = array("apple", "banana", "orange");
$firstFruit = array_shift($fruits);
echo $firstFruit;

输出结果:

apple

4. array_unshift(): 在数组的开头插入一个或多个元素

案例:

$fruits = array("banana", "orange");
array_unshift($fruits, "apple", "grape");
print_r($fruits);

输出结果:

Array
(
    [0] => apple
    [1] => grape
    [2] => banana
    [3] => orange
)

5. array_merge(): 合并一个或多个数组

案例:

$fruits1 = array("apple", "banana");
$fruits2 = array("orange", "grape");
$mergedFruits = array_merge($fruits1, $fruits2);
print_r($mergedFruits);

输出结果:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)

6. array_slice(): 从数组中取出一段元素

案例:

$fruits = array("apple", "banana", "orange", "grape", "watermelon");
$slicedFruits = array_slice($fruits, 2, 3);
print_r($slicedFruits);

输出结果:

Array
(
    [0] => orange
    [1] => grape
    [2] => watermelon
)

7. array_reverse(): 返回一个单元顺序相反的数组

案例:

$fruits = array("apple", "banana", "orange");
$reversedFruits = array_reverse($fruits);
print_r($reversedFruits);

输出结果:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)

8. array_key_exists(): 检查数组中是否存在指定的键名

案例:

$fruits = array("apple" => "red", "banana" => "yellow", "orange" => "orange");
if (array_key_exists("apple", $fruits)) {
    echo "The key 'apple' exists in the array.";
} else {
    echo "The key 'apple' does not exist in the array.";
}

输出结果:

The key 'apple' exists in the array.

9. in_array(): 检查数组中是否存在指定的值

案例:

$fruits = array("apple", "banana", "orange");
if (in_array("apple", $fruits)) {
    echo "The value 'apple' exists in the array.";
} else {
    echo "The value 'apple' does not exist in the array.";
}

输出结果:

The value 'apple' exists in the array.

10. array_search(): 查找指定的值在数组中的键名,并返回 个匹配的键名

案例:

$fruits = array("apple", "banana", "orange");
$key = array_search("banana", $fruits);
echo "The value 'banana' is associated with the key: " . $key;

输出结果:

The value 'banana' is associated with the key: 1

这是10个常用的PHP数组函数及对应的案例,通过这些函数可以方便地对数组进行操作,提高开发效率。