In PHP development, arrays are one of the most commonly used data structures. To find the key name associated with a specific value in an array, PHP offers the built-in array_search() function — a straightforward and efficient solution.
mixed array_search( mixed $needle , array $haystack [, bool $strict = false ] )
This function accepts three parameters:
Here is a simple example using array_search() to find a string value:
$fruits = array("banana", "apple", "orange", "grape");
<p>$key = array_search("apple", $fruits);</p>
<p>echo "The key for 'apple' is: " . $key;
Output:
The key for 'apple' is: 1
In this example, we created an array of fruits, then used array_search() to find the key name associated with "apple". The result returned the index 1.
When you want to compare not only the value but also the type, you can set the third parameter $strict to true. Here's an example:
$fruits = array("banana", 1, "2", true);
<p>$key = array_search(1, $fruits, true);<br>
echo "The key for 1 is: " . $key . "\n";</p>
<p>$key = array_search("1", $fruits, true);<br>
echo "The key for '1' is: " . $key;
Output:
The key for 1 is: 1
The key for '1' is:
Because strict mode is enabled, 1 (an integer) and "1" (a string) are considered unequal, so the second search returns false (no match found).
In summary, array_search() is a very practical function for array handling in PHP. Whether you're working with indexed arrays or associative ones, this function allows you to locate values and retrieve their keys quickly and reliably. It's especially useful when efficient data lookup is needed in your code.