
array()
函数法
$languages = array("PHP", "JavaScript", "Python");
$scores = array(2 => 90, 5 => 85, 8 => 92);
[]
$languages = ["PHP", "JavaScript", "Python"];
$scores = [2 => 90, 5 => 85, 8 => 92];
array()
函数创建
$user = array(
"username" => "code_master",
"email" => "code@example.com",
"join_date" => "2023-01-15"
);
$user = [
"username" => "code_master",
"email" => "code@example.com",
"join_date" => "2023-01-15"
];
$users = [
[
"username" => "code_master",
"email" => "code@example.com"
],
[
"username" => "design_pro",
"email" => "design@example.com"
]
];
$users
是一个数组,每个元素又是一个关联数组,代表一个用户。如果需要更复杂的结构,还可以创建三维甚至更高维的数组,比如 “用户组→用户→用户详情” 的三层结构。[]
添加元素,PHP 会自动分配递增键名:
$hobbies = []; // 声明空数组
$hobbies[] = "reading";
$hobbies[] = "coding";
$hobbies[] = "hiking";
$hobbies
会变成[0 => "reading", 1 => "coding", 2 => "hiking"]
。
$product = [];
$product["name"] = "PHP编程指南";
$product["price"] = 59.9;
$product["stock"] = 100;
$mixed = [10, "hello", true, 3.14];
$arr = ["a" => 1, "a" => 2]; // 最终"a"的值为2