在php中使用unset删除元素后,并不会重建数组的索引 由于没有重建索引,在unset之后继续使用之前的索引会报错,此时可以用 array_values 重建数组索引。 $arr = array(1,2,3,4);unset($arr[1]);echo $array[1]; // error undefined offsetprint_r($arr); //
在php中使用unset删除元素后,并不会重建数组的索引
由于没有重建索引,在unset之后继续使用之前的索引会报错,此时可以用array_values重建数组索引。
$arr = array(1,2,3,4);unset($arr[1]);echo $array[1]; // error undefined offsetprint_r($arr); // 输出如下/**array( [0] => 1 [2] => 3 [3] => 4)**/$arr = array_values($arr);print_r($arr);// 输出如下/**array( [0] => 1 [1] => 3 [2] => 4)**/
referencehttp://stackoverflow.com/questions/5943149/rebase-array-keys-after-unsetting-elements 原文地址:php数组中unset元素之后重建索引, 感谢原作者分享。