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.
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: 1This 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 . "\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 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.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.