This post will discuss how to find the key from a value in an array in PHP.

The array_search() function searches an array for the specified value and returns the first matching key if the value is found in the array.

Download  Run Code

 
If the value is not found in the array, the array_search() function returns the boolean false or a non-boolean value evaluating to false. It also takes a third parameter, strict for performing strict type comparisons. If true, the function will search for identical elements in the array.

Download  Run Code

2. Using array_keys() function

The array_search() function returns the first matching key if the value is found in the array more than once. To return the keys for all matching values, use array_keys() with the search parameter instead.

Download  Run Code

 
Like array_search(), array_keys() accepts a boolean parameter indicating strict type comparison. Pass true to search for identical elements in the array.

Download  Run Code

3. Using array_flip() function

If your array contains distinct int or string values, you can create an array with its order flipped, where keys become values and values become keys. This can be easily achieved with the array_flip() function, as shown below. If a value is repeated multiple times, the latest key will be used as its value.

Download  Run Code

That’s all about finding the key from a value in an array in PHP.