按值删除数组项 [英] Removing array item by value
本文介绍了按值删除数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要删除具有给定值的数组项:
I need to remove array item with given value:
if (in_array($id, $items)) {
$items = array_flip($items);
unset($items[ $id ]);
$items = array_flip($items);
}
能否以更短(更有效)的方式完成?
Could it be done in shorter (more efficient) way?
推荐答案
怎么样:
if (($key = array_search($id, $items)) !== false) unset($items[$key]);
或多个值:
while(($key = array_search($id, $items)) !== false) {
unset($items[$key]);
}
这也可以防止密钥丢失,这是 array_flip()
的副作用.
This would prevent key loss as well, which is a side effect of array_flip()
.
这篇关于按值删除数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文