插件窝 干货文章 php声明数组方法

php声明数组方法

数组 array apple 函数 131    来源:    2025-03-19

在PHP中,声明数组有多种方法。以下是几种常见的声明数组的方式:

1. 使用 array() 函数

这是PHP中最传统的声明数组的方式。

$array = array("apple", "banana", "cherry");

2. 使用短数组语法 [](PHP 5.4及以上版本)

从PHP 5.4开始,可以使用更简洁的短数组语法来声明数组。

$array = ["apple", "banana", "cherry"];

3. 声明关联数组

关联数组是指数组的键是字符串而不是数字。

$array = array(
    "fruit1" => "apple",
    "fruit2" => "banana",
    "fruit3" => "cherry"
);

// 或者使用短数组语法
$array = [
    "fruit1" => "apple",
    "fruit2" => "banana",
    "fruit3" => "cherry"
];

4. 声明多维数组

多维数组是指数组中的元素也是数组。

$array = array(
    array("apple", "banana", "cherry"),
    array("carrot", "potato", "tomato")
);

// 或者使用短数组语法
$array = [
    ["apple", "banana", "cherry"],
    ["carrot", "potato", "tomato"]
];

5. 动态添加元素到数组

你可以在声明数组后,动态地向数组中添加元素。

$array = []; // 声明一个空数组
$array[] = "apple"; // 添加元素
$array[] = "banana";
$array[] = "cherry";

6. 使用 range() 函数生成数组

range() 函数可以生成一个包含指定范围内元素的数组。

$numbers = range(1, 10); // 生成1到10的数组

7. 使用 explode() 函数从字符串生成数组

explode() 函数可以将字符串按指定的分隔符拆分为数组。

$string = "apple,banana,cherry";
$array = explode(",", $string); // 生成数组 ["apple", "banana", "cherry"]

8. 使用 array_fill() 函数生成数组

array_fill() 函数可以生成一个包含指定数量相同元素的数组。

$array = array_fill(0, 5, "apple"); // 生成数组 ["apple", "apple", "apple", "apple", "apple"]

9. 使用 array_combine() 函数生成关联数组

array_combine() 函数可以将两个数组合并为一个关联数组。

$keys = ["fruit1", "fruit2", "fruit3"];
$values = ["apple", "banana", "cherry"];
$array = array_combine($keys, $values); // 生成数组 ["fruit1" => "apple", "fruit2" => "banana", "fruit3" => "cherry"]

10. 使用 array_map() 函数生成数组

array_map() 函数可以对数组中的每个元素应用回调函数,并返回一个新的数组。

$numbers = [1, 2, 3];
$squared = array_map(function($n) {
    return $n * $n;
}, $numbers); // 生成数组 [1, 4, 9]

总结

PHP提供了多种灵活的方式来声明和操作数组,开发者可以根据具体需求选择合适的方法。