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.