php开发常用的数组函数及简单demo

Author: 陌小雨Date: 2023-07-08View: 54

PHP中常用的数组函数非常多,以下是一些常用的数组函数及简单示例:

  1. array():创建数组
$fruits = array("apple", "banana", "cherry");
  1. count():返回数组中元素的个数
$fruits = array("apple", "banana", "cherry");
echo count($fruits); // 输出 3
  1. array_push():向数组末尾添加一个或多个元素
$fruits = array("apple", "banana");
array_push($fruits, "cherry", "date");
print_r($fruits); // 输出Array ( [0] => apple [1] => banana [2] => cherry [3] => date )
  1. array_pop():从数组末尾删除一个元素并返回该元素
$fruits = array("apple", "banana", "cherry");
$last_fruit = array_pop($fruits);
echo $last_fruit; // 输出 cherry
  1. array_shift():从数组开头删除一个元素并返回该元素
$fruits = array("apple", "banana", "cherry");
$first_fruit = array_shift($fruits);
echo $first_fruit; // 输出 apple
  1. array_unshift():向数组开头添加一个或多个元素
$fruits = array("apple", "banana");
array_unshift($fruits, "cherry", "date");
print_r($fruits); // 输出Array ( [0] => cherry [1] => date [2] => apple [3] => banana )
  1. array_merge():合并一个或多个数组
$fruits1 = array("apple", "banana");
$fruits2 = array("cherry", "date");
$all_fruits = array_merge($fruits1, $fruits2);
print_r($all_fruits); // 输出Array ( [0] => apple [1] => banana [2] => cherry [3] => date )
  1. array_slice():从数组中取出一段
$fruits = array("apple", "banana", "cherry", "date", "elderberry");
$slice_fruits = array_slice($fruits, 1, 3);
print_r($slice_fruits); // 输出Array ( [0] => banana [1] => cherry [2] => date )
  1. array_search():在数组中查找一个值并返回其键名
$fruits = array("apple", "banana", "cherry");
$key = array_search("banana", $fruits);
echo $key; // 输出 1
  1. in_array():检查一个值是否在数组中
$fruits = array("apple", "banana", "cherry");
$result = in_array("banana", $fruits);
echo $result; // 输出 1