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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false

Parameters

ParameterDescription
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

Find a keyTry it yourself
<?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
Check with !== falseTry it yourself
<?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

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?