在PHP中,有以下三种类型的数组:
可以使用array()函数或简写的中括号[]来定义数组。
// 使用array()函数定义索引数组
$colors = array("Red", "Green", "Blue");
// 使用中括号[]定义关联数组
$person = [
"name" => "Tom",
"age" => 30,
"gender" => "Male"
];
可以使用以下函数来操作数组:
示例:
// 访问数组元素
echo $colors[0]; // 输出 "Red"
echo $person["name"]; // 输出 "Tom"
// 遍历索引数组
foreach ($colors as $value) {
echo $value . " ";
}
// 输出 "Red Green Blue"
// 遍历关联数组
foreach ($person as $key => $value) {
echo $key . ": " . $value . " ";
}
// 输出 "name: Tom age: 30 gender: Male"
// 添加和删除元素
array_push($colors, "Yellow");
array_pop($colors);
array_unshift($colors, "Orange");
array_shift($colors);
// 合并数组
$fruits1 = ["Apple", "Banana"];
$fruits2 = ["Orange", "Grape"];
$fruits = array_merge($fruits1, $fruits2);
// 查找元素
$index = array_search("Green", $colors);
if ($index !== false) {
echo "Found at index " . $index;
}
// 检查键名是否存在
if (array_key_exists("name", $person)) {
echo "Name exists";
}