I have an array with several elements. The array keys are numeric.
I now want to remove a certain element. All I know is the element's content, not the key.
Is there an easy way to remove this element from the array? Or do I need to loop through all elements of the array to get the key and then unset the element with that key?
-
for the several elements it doesn't really matter.Your Common Sense– Your Common Sense2010年11月28日 11:50:18 +00:00Commented Nov 28, 2010 at 11:50
4 Answers 4
You can use array_filter
to remove all elements with that particular value:
$arr = array_filter($arr, function($val) { return $val !== 'some value'; });
This example uses an anonymous function that were introduced with PHP 5.3. But you can use any other callback function.
Or you can use array_keys
to get the keys of all elements with that value and do a diff on the keys after:
$arr = array_diff_key($arr, array_flip(array_keys($arr, 'some value', true)));
6 Comments
array_filter
function, seems to be really handy.array_search
and array_filter
is O(n). And array_flip
is only applied of an array of keys; so there won’t be any information loss.array_search
versus Θ(n) for array_filter
; but it’s still O(n) in both cases.You can use the array search function to get the key
$key = array_search('searchterm', $items);
unset($items[$key]);
1 Comment
array_search
(see my answer below)sure
foreach($myarray as $key=>$item) {
if($item=='myknowncontent') { unset($myarray[$key]; }
}
7 Comments
for the several elements it doesn't really matter
break
operator.You can use array_search to find the corresponding key:
$key = array_search("whatever", $array);
if ($key !== FALSE)
unset($array[$key]);
1 Comment
$array[0]
if there is no element with such value.