12

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?

5 Answers 5

31

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

Sign up to request clarification or add additional context in comments.

Comments

12

https://www.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.

1 Comment

Very nice, wasn't familiar with array_fliter
4

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

Comments

3

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

3 Comments

And what does this code do if the array doesn't contain any strawberries?
and what if strawberries is in the input array twice?
Most days aren't my day either!
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.