涉及2个功能。
$array = array("first", "second", "third", "fourth");
foreach($array as $i=> $string) {
if(stristr($string, "e")) {
unset($array[$i]);
}
}
second
是字符为'e'的数组项。如果其unset
,$array[1]
将为空:
$array[0] = "first"
$array[1] = ""
$array[2] = "third"
$array[3] = "fourth"
我希望$array[1]
从数组中删除(例如在array_shift()
中),以便third
取代second
和fourth
这个地方third
:
$array[0] = "first"
$array[1] = "third"
$array[2] = "fourth"
答案 0 :(得分:85)
$array = array_values($array);
答案 1 :(得分:4)
我认为我找到的最佳解决方案是:
如果您只想删除一个元素:
array_splice($array,1,1); // all keys will be reindexed from 0
其中第二个和第三个参数是偏移(键)和长度(要删除的数量)
最好删除多个密钥:使用array_filter()
删除数组中的所有空字符串和falsey值,然后array_splice()
重新排序:
array_splice(array_filter($array), 0, 0);