开发者

remove element from array based on its value?

开发者 https://www.devze.com 2022-12-18 19:39 出处:网络
i\'ve got a regular array with keys and values. is there a simple way to remove the array element based on its value or do i have to foreach-loop it through and check eve开发者_运维知识库ry value to

i've got a regular array with keys and values.

is there a simple way to remove the array element based on its value or do i have to foreach-loop it through and check eve开发者_运维知识库ry value to remove it?


array_diff:

$array = array('a','b','c');
$array_to_remove = array('a');

$final_array = array_diff($array,$array_to_remove);
// array('b','c');

edit: for more info: http://www.php.net/array_diff


http://us3.php.net/array_filter

PHP 5.3 example to remove "foo" from array $a:

<?php
$a = array("foo", "bar");
$a = array_filter($a, function($v) { return $v != "foo"; });
?>

The second parameter can be any kind of PHP callback (e.g., name of function as a string). You could also use a function generating function if the search value is not constant.


You should be able to do that with a combination of array_search() and array_splice().

Untested, but should work for arrays that contain the value only once:

$array = array("Apples", "strawberries", "pears");
$searchpos = array_search("strawberries", $array);
if ($searchpos !== FALSE) {
  array_splice($array, $searchpos, 1);
}


Short Answerunset($array[array_search('value', $array)]);

Explanation

  1. Find key by its value: $key = array_search('value', $array);
  2. remove array element by its key: unset($array[$key]);


If your array does have unique values, you can flip them with array_flip

0

精彩评论

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

关注公众号