tags:

views:

109

answers:

4

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 every value to remove it?

+2  A: 

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 = array_splice($array, $searchpos, 1);
Pekka
And what does this code do if the array doesn't contain any strawberries?
Tobias Cohen
Good point, thanks. Modified the code to check for that.
Pekka
and what if strawberries is in the input array twice?
Mike Sherov
Today is not my day to answer PHP questions :) @Mike, I'd +1 you but I have no votes left.
Pekka
Most days aren't my day either!
Mike Sherov
A: 

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

Pentium10
+10  A: 

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

Mike Sherov
+3  A: 

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.

konforce
Very nice, wasn't familiar with array_fliter
Erik