Find the key from a value in an array in PHP
This post will discuss how to find the key from a value in an array in PHP.
1. Using array_search() function
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $arr = array('One' => 1, 'Two' => 2, 'Three' => 3); $val = '2'; $key = array_search($val, $arr); echo $key; /* Output: Two */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $arr = array('One' => 1, 'Two' => 2, 'Three' => 3); $val = '2'; $key = array_search($val, $arr, true); echo $key; /* Output: */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $arr = array('One' => 1, 'Two' => 2, '2' => 2, 'Three' => 3); $val = 2; $keys = array_keys($arr, $val); print_r($keys); /* Output: Array ( [0] => Two [1] => 2 ) */ ?> |
Like array_search(), array_keys() accepts a boolean parameter indicating strict type comparison. Pass true to search for identical elements in the array.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $arr = array('One' => 1, 'Two' => 2, '2' => 2, 'Three' => 3); $val = '2'; $keys = array_keys($arr, $val, true); print_r($keys); /* Output: Array() */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $arr = array('One' => 1, 'Two' => 2, 'Three' => 3); $val = 2; $array = array_flip($arr); echo $array[$val]; /* Output: Two */ ?> |
That’s all about finding the key from a value in an array in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)