Skip to content

Latest commit

 

History

History
22 lines (16 loc) · 710 Bytes

File metadata and controls

22 lines (16 loc) · 710 Bytes

PHP 使用 unset 删除数组元素并重新格式化键名

在 PHP 中使用 unset 删除数组中的某个元素后,数组的键名不会自动重置为连续的数字索引。例如,删除一个元素后,数组可能会变成非连续的数字键数组。

示例:

$array = [1, 2, 3, 4];
unset($array[1]); // 删除第二个元素
print_r($array);
// 输出:Array ( [0] => 1 [2] => 3 [3] => 4 )

如上所示,unset 操作使数组的键变成 [0, 2, 3],而不是连续的 [0, 1, 2]。

使用 array_values函数将数组重新格式化为连续的数字索引:

$array = array_values($array);
print_r($array);
// 输出:Array ( [0] => 1 [1] => 3 [2] => 4 )