Tutorial :remove element from array based on its value?



Question:

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?


Solution:1

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.


Solution:2

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


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


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


Solution:5

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »