PHP 8 reference · Array Functions
PHP array_search() Function
Search an array for a value and return the first matching key, or false if it isn't there.
PHP 8 Since 4.0
Syntax
array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false
Parameters
| Parameter | Description |
|---|---|
needle |
The value to find. |
haystack |
The array to search. |
strict optional |
true compares with ===. Default: false |
Return value
The key of the first match, or false.
Examples
<?php
$colors = ["red", "green", "blue"];
echo array_search("blue", $colors), "\n";
$codes = ["us" => "USA", "fr" => "France"];
echo array_search("France", $codes), "\n";
Output
2 fr
<?php
$key = array_search("red", ["red", "green"]);
if ($key !== false) {
echo "found at $key\n"; // 0 is a valid key
}
Output
found at 0
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
list.index()· Pythonarray.indexOf()· JavaScript
Related
in_array()· Check whether a value exists in an array. Pass true as the third argument for a strict (===) comparison.array_keys()· Return all the keys of an array, or only the keys whose value matches a search value.array_find_key()· Return the key of the first element for which a callback returns true, or null if none match. Added in PHP 8.4.- PHP Arrays · tutorial
- PHP Array Functions · tutorial