Current Location: Home> Latest Articles> Quickly Find Array Keys Using PHP's array_search Function

Quickly Find Array Keys Using PHP's array_search Function

M66 2025-06-05

The Purpose of PHP's array_search Function

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.

Basic Syntax of array_search()

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

This function accepts three parameters:

  • $needle: The value to search for.
  • $haystack: The array to search within.
  • $strict: Optional. Defaults to false. If set to true, the function will also compare the types of the values, not just their values.

Basic Usage Example

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.

Using Strict Mode

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).

Important Notes on array_search

  • If the array contains multiple matching values, array_search() will return the key of the first match only.
  • The returned key may be an integer (for indexed arrays) or a string (for associative arrays).
  • If no match is found, the function returns false.

Conclusion

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.