Remove input from an array by its value

5

To remove an entry from an array, we can use the unset () function: / p>

<?php
$arr = array(1, 2);

unset($arr[0]);

var_dump($arr);
/*
Resultado:
array(1) {
  [1]=&gt;
  int(2)
}
*/
?>

Question

How to remove an entry from an array by its value instead of its position?

Using the example above, we would pass the value 1 instead of the 0 position.

    
asked by anonymous 28.01.2014 / 00:45

2 answers

5

To remove an item from the array by passing the value, the function array_search () , solve. It retries the key if the value is found in the array and then just pass the index to unset() . This function does not reorder the array.

   
$arr = array(1,2,3,4,5,6);
echo'<pre>ANTES';
print_r($arr);

$key = array_search(4, $arr);
unset($arr[$key]);



echo'<pre>DEPOIS';
print_r($arr);

output:

   
ANTESArray
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)

DEPOISArray
(
    [0] => 1
    [1] => 2
    [2] => 3
    [4] => 5
    [5] => 6
)
    
28.01.2014 / 01:04
1

I was able to think of two ways to do this:

1 - Using array_search and array_values

As already replied by @perdeu the function array_search() solves the problem of finding the value.

However, I'd like to add that the array_values function resolves the issue of reindexing, that is, it returns the original array values indexed from scratch.

See an example:

$array = array(1, 2, 3, 4);
$pos = array_search(2, $array); //buscar posição do segundo elemento
unset($array[$pos]); //remover elemento
$array = array_values($array); //recriar índice

The final output will be:

array(3) {
  [0]=> int(1)
  [1]=> int(3)
  [2]=> int(4)
}

See a working example here .

2 - Using array_splice

Another alternative is to use the array_splice() function, which allows you to replace a portion of an array by something else, which can be nothing . This function changes the original array and recreates the indexes.

Example:

$array = array(1, 2, 3, 4);
$pos = array_search(2, $array); //buscar posição do segundo elemento
array_splice($array, $pos, 1); //remove 1 elemento na posição encontrada

The result is the same as previously mentioned.

See the working code here .

    
28.01.2014 / 13:58