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 .