PHP array_search() Function

Quick summary: The PHP array_search() function searches for a value in an array and returns the corresponding key.

PHP array_search() Syntax

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

PHP array_search() Basic examples

$colors = ['red', 'green', 'blue'];
var_dump(array_search('green', $colors));
PHP
Output:
int(1)

Returns the key of the found value.

var_dump(array_search('yellow', ['red','green']));
PHP
Output:
bool(false)

Returns false when the value is not found.

PHP array_search() Real-world usage

$roles = ['admin','editor','viewer'];
if (array_search('admin', $roles) !== false) {
    echo 'Admin found';
}
PHP
Output:
Admin found

Checks whether a role exists in a list.

PHP array_search() Edge cases

var_dump(array_search(0, ['a', 0, 'b']));
PHP
Output:
int(1)

Searches using loose comparison by default.

PHP array_search() Common mistakes

Using loose comparison with array_search

A key of 0 can be misinterpreted as false.

Incorrect
if (array_search('red', ['red','blue'])) { }
Correct
if (array_search('red', ['red','blue']) !== false) { }

Always use strict comparison against false.

PHP array_search() Frequently Asked Questions

What does array_search() do?

array_search() returns the key of a value in an array.

What does it return if not found?

false.

Is it case-sensitive?

Yes.

Does it support strict mode?

Yes.

Does it modify array?

No.

Works with associative arrays?

Yes.

What if value appears multiple times?

First match is returned.

Difference from in_array()?

array_search returns key, in_array returns boolean.

Use case?

Finding index of element.

Performance?

Linear search.

Can return 0?

Yes, use strict comparison.

Supports all types?

Yes.

PHP array_search() Related PHP Functions