Backend Development 5 min read

Using PHP array_search to Find Keys in an Array

This article explains how the PHP array_search function works, describes its parameters, demonstrates basic and strict‑mode usage with code examples, and highlights important considerations such as duplicate values and type‑strict searching.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP array_search to Find Keys in an Array

In PHP development, arrays are a common and useful data structure, and the array_search function can be used to locate the key associated with a specific value.

The basic syntax of the function is:

mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

The three parameters are:

$needle : the value to search for.

$haystack : the array to search in.

$strict (optional): when true , the comparison is type‑strict; the default false compares values without type checking.

Example – finding the key of "apple" in a simple fruit array:

$fruits = array("banana", "apple", "orange", "grape");
$key = array_search("apple", $fruits);
echo "The key for 'apple' is: " . $key;

The output will be:

The key for 'apple' is: 1

If the searched value appears multiple times, array_search returns only the first matching key.

When strict comparison is required, set the third argument to true . The following example shows strict mode with mixed types:

$fruits = array("banana", 1, "2", true);
$key = array_search(1, $fruits, true);
echo "The key for 1 is: " . $key . "\n";
$key = array_search("1", $fruits, true);
echo "The key for '1' is: " . $key;

The output will be:

The key for 1 is: 1
The key for '1' is:

In this strict‑mode example, the numeric 1 and the string '1' are considered different, so the second search returns false (no key).

In summary, array_search provides a convenient way to locate a value’s key in an array; it returns the first match by default, and setting $strict to true enables type‑strict searching.

Java learning materials

C language learning materials

Frontend learning materials

C++ learning materials

PHP learning materials

backendPHPphp-functionsarray-manipulationarray-search
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.