php – Remove input from an array by its value

Question:

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

<?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 position 0 .

Answer:

To remove an item from the array by passing the value, the array_search() function solves. It returns 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);

exit:

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

DEPOISArray
(
    [0] => 1
    [1] => 2
    [2] => 3
    [4] => 5
    [5] => 6
)
Scroll to Top