开发者

Deleting an array element with PHP

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 a开发者_如何学Pythonnd then unset the element with that key?


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)));


You can use the array search function to get the key

$key = array_search('searchterm', $items); 
unset($items[$key]);


sure

foreach($myarray as $key=>$item) {
    if($item=='myknowncontent') { unset($myarray[$key]; }
}


You can use array_search to find the corresponding key:

$key = array_search("whatever", $array);
if ($key !== FALSE)
   unset($array[$key]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜