What does array_search() do?
array_search() looks for $needle among the array values and returns the key of the first match, or false if nothing matches. Like in_array() it compares loosely unless strict mode is enabled.
Syntax
array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false
Parameters
$needle- The value to search for.$haystack- The array to search.$strict- When true, uses===so types must match.
Return value
The key (int or string) of the first match, or false. Because a key can be 0, always test the result with !== false.
array_search() examples
Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.
1. Find the index of a value
<?php
$colors = ["red", "green", "blue"];
var_dump(array_search("blue", $colors));
var_dump(array_search("red", $colors));
var_dump(array_search("pink", $colors));
Output:
int(2) int(0) bool(false)
2. Associative arrays, strict mode and the key-0 trap
<?php
$stock = ["apples" => 0, "pears" => 12, "plums" => "12"];
var_dump(array_search(12, $stock));
var_dump(array_search("12", $stock, true));
$key = array_search("red", ["red", "green"]);
if ($key !== false) {
echo "Found at index $key\n";
}
Output:
string(5) "pears" string(5) "plums" Found at index 0
3. Search a multidimensional array
array_column() extracts one field from every row, then array_search() finds its position. This works when the outer array has sequential keys (0, 1, 2 ...). Use array_keys() to get every matching key.
<?php
$users = [
["id" => 10, "name" => "Ann"],
["id" => 20, "name" => "Ben"],
["id" => 30, "name" => "Cara"],
];
$index = array_search("Ben", array_column($users, "name"));
echo "Ben is at index $index, id " . $users[$index]["id"] . "\n";
print_r(array_keys([1, 2, 1, 3, 1], 1));
Output:
Ben is at index 1, id 20
Array
(
[0] => 0
[1] => 2
[2] => 4
)
Common mistakes and gotchas
- Key 0:
if (array_search(...))fails when the match is at key 0. Compare with!== false. - First match only: use
array_keys($array, $value)to get all keys. - Non-sequential keys:
array_column()re-indexes, so the found index may not be a valid key of the original array. Usearray_column($rows, "name", "id")or a loop in that case.