Home > php教程 > php手册 > PHP数组中unset元素之后重建索引

PHP数组中unset元素之后重建索引

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:08:17
Original
2715 people have browsed it

在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 offset
print_r($arr); 
// 输出如下
/**
Array
(
    [0] => 1
    [2] => 3
    [3] => 4
)
**/
$arr = array_values($arr);
print_r($arr);
// 输出如下
/**
Array
(
    [0] => 1
    [1] => 3
    [2] => 4
)
**/
Copy after login

reference

  • http://stackoverflow.com/questions/5943149/rebase-array-keys-after-unsetting-elements
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template