您的位置:首页 > 编程语言 > PHP开发

php如何从数组中删除一个元素

2012-06-04 20:48 806 查看
(原文:http://stackoverflow.com/questions/369602/how-to-delete-an-element-from-an-array-in-php

It should be noted that
unset()
will
keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:
$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[3]=>
int(3)
} */

$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */


So
array_splice()
can
be used if you'd like to normalize your integer keys. Another option is using
array_values()
after
unset()
:
$array = array(0, 1, 2, 3);

unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: