PHP 索引数组的基本概念
索引数组是 PHP 中最常见的数组类型之一,它以数字作为键名,默认从 0 开始递增。索引数组适用于存储有序的数据集合,例如列表或序列。
$fruits = array("Apple", "Banana", "Orange");
// 或使用短数组语法
$fruits = ["Apple", "Banana", "Orange"];
创建索引数组
可以通过多种方式创建索引数组。使用 array()
函数或简化的方括号语法 []
是最常见的方法。
// 使用 array() 函数
$colors = array("Red", "Green", "Blue");
// 使用短数组语法
$colors = ["Red", "Green", "Blue"];
访问索引数组元素
通过数字索引可以访问数组中的元素,索引从 0 开始。
$fruits = ["Apple", "Banana", "Orange"];
echo $fruits[0]; // 输出: Apple
echo $fruits[1]; // 输出: Banana
echo $fruits[2]; // 输出: Orange
修改索引数组元素
可以通过索引直接修改数组中的元素。
$fruits = ["Apple", "Banana", "Orange"];
$fruits[1] = "Mango";
print_r($fruits);
// 输出: Array ( [0] => Apple [1] => Mango [2] => Orange )
遍历索引数组
使用 for
循环或 foreach
循环可以遍历索引数组的所有元素。
$fruits = ["Apple", "Banana", "Orange"];
// 使用 for 循环
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "\n";
}
// 使用 foreach 循环
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
添加元素到索引数组
可以使用 array_push()
函数或在数组末尾直接赋值的方式添加新元素。
$fruits = ["Apple", "Banana"];
// 使用 array_push()
array_push($fruits, "Orange");
// 直接赋值
$fruits[] = "Mango";
print_r($fruits);
// 输出: Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Mango )
删除索引数组元素
可以使用 unset()
函数删除特定索引的元素,但注意删除后索引不会自动重新排列。
$fruits = ["Apple", "Banana", "Orange"];
unset($fruits[1]);
print_r($fruits);
// 输出: Array ( [0] => Apple [2] => Orange )
如果需要重新索引数组,可以使用 array_values()
函数。
$fruits = array_values($fruits);
print_r($fruits);
// 输出: Array ( [0] => Apple [1] => Orange )
合并索引数组
使用 array_merge()
函数可以合并多个索引数组。
$fruits1 = ["Apple", "Banana"];
$fruits2 = ["Orange", "Mango"];
$combined = array_merge($fruits1, $fruits2);
print_r($combined);
// 输出: Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Mango )
检查索引数组长度
使用 count()
函数可以获取数组的长度。
$fruits = ["Apple", "Banana", "Orange"];
echo count($fruits); // 输出: 3
索引数组的排序
PHP 提供了多种排序函数,例如 sort()
和 rsort()
,分别用于升序和降序排序。
$numbers = [3, 1, 4, 2];
// 升序排序
sort($numbers);
print_r($numbers); // 输出: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
// 降序排序
rsort($numbers);
print_r($numbers); // 输出: Array ( [0] => 4 [1] => 3 [2] => 2 [3] => 1 )
多维索引数组
索引数组可以嵌套形成多维数组,适用于存储更复杂的数据结构。
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo $matrix[1][2]; // 输出: 6
使用 array_slice() 截取部分数组
array_slice()
函数可以截取数组的一部分。
$fruits = ["Apple", "Banana", "Orange", "Mango"];
$slice = array_slice($fruits, 1, 2);
print_r($slice);
// 输出: Array ( [0] => Banana [1] => Orange )
使用 array_search() 查找元素
array_search()
函数可以查找数组中某个值的索引。
$fruits = ["Apple", "Banana", "Orange"];
$index = array_search("Banana", $fruits);
echo $index; // 输出: 1
通过这些方法和示例,可以灵活地操作 PHP 索引数组,满足不同的开发需求。