Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP array_search function

The array_search function searches the array for a value that corresponds to the given value. If the given value is found in the array, it will return its key

Description / Descripción
array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false


  • $needle: the value that will be searched. If this value is a string, the comparison will be case-sensitive.
  • $haystack: the array where we will look for the value given in $needle.
  • $strict: this parameter indicates whether the search will be identical or equal. If it is true, the comparison will be === instead of ==. Objects should be of the same instance if strict is true.


Returns the corresponding key for the searched value in the array; otherwise, it will return false. This will return the key where the searched value first appears.

You can obtain the keys for all values where the searched value is found. This can be done using the array_keys function and the search_value option.

You can learn more about array_keys at

Ejemplo de PHP array_search

In this example, we have used an associative array, but we must consider other cases because the returned value can also be 0, and this is something to be aware of since the value 0 can be evaluated as false

// Definir un array de autos
$autos = array(
    "Toyota" => "Camry",
    "Honda" => "Civic",
    "Ford" => "Focus",
    "Chevrolet" => "Malibu"

// Buscar la posición del modelo "Civic" en el array
$posicion = array_search("Civic", $autos);

// Verificar si se encontró y mostrar el resultado
if ($posicion !== false) {
    echo "La posición del modelo 'Civic' en el array de autos es: " . $posicion;
} else {
    echo "El modelo 'Civic' no se encontró en el array de autos";
La posición del modelo 'Civic' en el array de autos es: Honda
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category