php数组
1.创建数组
// 创建数字索引数组
$numbers = array(1, 2, 3, 4, 5);
// PHP 5.4以后可以简写
$numbers = [1, 2, 3, 4, 5];
// 创建关联数组
$associative = array("one" => 1, "two" => 2, "three" => 3);
// PHP 5.4以后可以简写
$associative = ["one" => 1, "two" => 2, "three" => 3];
2.访问数组元素
$numbers = [1, 2, 3, 4, 5];
echo $numbers[0]; // 输出 1
$associative = ["one" => 1, "two" => 2, "three" => 3];
echo $associative["two"]; // 输出 2
3.遍历数组
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as $number) {
echo $number . "\n";
}
$associative = ["one" => 1, "two" => 2, "three" => 3];
foreach ($associative as $key => $value) {
echo $key . ": " . $value . "\n";
}
4.在数组中添加和删除元素
$numbers = [1, 2, 3, 4, 5];
$numbers[] = 6; // 添加元素
unset($numbers[5]); // 删除元素
$associative = ["one" => 1, "two" => 2, "three" => 3];
$associative["four"] = 4; // 添加元素
unset($associative["three"]); // 删除元素
5.数组函数
$numbers = [1, 2, 3, 4, 5];
$sum = array_sum($numbers); // 计算数组之和
$associative = ["one" => 1, "two" => 2, "three" => 3];
$keys = array_keys($associative); // 获取所有键
$values = array_values($associative); // 获取所有值
6.多维数组
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo $matrix[1][1]; // 输出 5
|