Using PHP's array_search Function to Find Keys by Value

This article explains how to use PHP's array_search function to locate the key of a specific value in an array, covering its syntax, parameters, basic and strict mode examples, and important considerations such as handling duplicate values and type-sensitive searches.

php Courses
php Courses
php Courses
Using PHP's array_search Function to Find Keys by Value

In PHP development, arrays are a common data structure, and the built-in array_search function can be used to find the key name associated with a specific value.

The basic syntax of array_search is:

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

The function accepts three parameters: $needle: the value to search for. $haystack: the array to search in. $strict (optional): when set to true, the comparison is type‑strict; default is false.

Example: given an array $fruits containing several fruit names, we can locate the key of "apple" as follows:

$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

This demonstrates that the function returns the first matching key. If the searched value appears multiple times, only the first occurrence is returned.

When a strict type comparison is required, set the third argument $strict 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 . "
";

$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 strict mode, the integer 1 does not match the string "1", so the second search returns false. The array_search function is therefore useful for quickly locating values in arrays, with optional strict type checking.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendphp-functionsarray_searcharray-manipulation
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

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.