PHP array_values 函数
最后修改于 2025 年 3 月 13 日
PHP array_values 函数从数组中返回所有值,并对数组进行数值索引。它对于重新索引数组非常有用。
基本定义
array_values 函数提取数组中的所有值。它返回一个具有从 0 开始的顺序数值键的新数组。
语法:array_values(array $array): array。该函数保留值的顺序,但将所有键重置为数值索引。
基本的 array_values 示例
这演示了如何从具有字符串键的关联数组中提取值。
basic_array_values.php
<?php
$user = [
'name' => 'John Doe',
'email' => 'john@example.com',
'age' => 30
];
$values = array_values($user);
print_r($values);
这会提取关联数组中的所有值。输出将是:['John Doe', 'john@example.com', 30],具有数值索引。
重新索引数组
使用 array_values 在 unset 操作后重置数值键。
reindex_array.php
<?php $numbers = [10 => 'a', 20 => 'b', 30 => 'c']; unset($numbers[20]); $reindexed = array_values($numbers); print_r($reindexed);
删除元素 'b' 后,数组出现间隙。array_values 创建一个具有顺序键的新数组:[0 => 'a', 1 => 'c']。
处理混合数组
array_values 可用于包含不同值类型的数组。
mixed_array.php
<?php
$mixed = [
'a' => 'apple',
5 => 3.14,
'test' => true,
null
];
$values = array_values($mixed);
print_r($values);
该函数保留所有值,而不管其类型。输出包含:['apple', 3.14, true, null],具有新的数值索引。
使用 array_values 保留顺序
该函数维护数组中元素的原始顺序。
order_preservation.php
<?php
$unordered = [
10 => 'ten',
2 => 'two',
5 => 'five'
];
$ordered = array_values($unordered);
print_r($ordered);
尽管原始键不是连续的,但值会保留其顺序:['ten', 'two', 'five']。只有索引会变为连续的。
与其他函数结合使用
array_values 可以与 array_unique 等函数结合使用。
combined_functions.php
<?php $duplicates = ['a', 'b', 'a', 'c', 'b', 'd']; $unique = array_values(array_unique($duplicates)); print_r($unique);
这会删除重复项并重新索引数组。结果是:[0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd']。
最佳实践
- 内存使用:创建新数组,请考虑大数组的内存。
- 键保留:仅在键无关紧要时使用。
- 性能:对于大多数用例通常都很高效。
- 可读性:当只需要值时,使代码更清晰。
来源
本教程涵盖了 PHP array_values 函数,并通过实际示例展示了其在数组操作场景中的用法。
作者
列出 所有 PHP 数组函数。