Remove matrix input by its value

Asked

Viewed 353 times

5

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

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

unset($arr[0]);

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

Question

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

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

2 answers

5

To remove an item from the array by passing the value, the function array_search(), resolves. It resumes the key if the value is found in the array and then just pass the Indice 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
)

1

I could think of two ways to do that:

1 - Using array_search and array_values

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

However, I would like to add that the function array_values solves the reindexation issue, i.e., it returns the values of the original array indexed from scratch.

Take 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 exit will be:

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

See a functional example here.

2 - Using array_splice

Another alternative is to use the function array_splice(), that allows you to replace a chunk of an array with something else, which can be nothingness. 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 quoted above.

See the code working here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.