How to get the array key for a given value in PHP?
Suppose we have an array of key and value pairs and we don’t know the keys of that array. We know are only values of the array.
Now we want to get the array key for a value without knowing the key. How can we do that?
Well, PHP has a function which can get the key for a given value of an array. If same value is in the array for multiple times then it will return the first key.
The function we are talking about is PHP array_search(). The array_search function of PHP can return the array key name by the value of the key.
Below is the simple syntax of this PHP function:
Now see an example:
Let’s assume we have the array that is given below:
$arr = array( 0 => 'book', 1 => 'pen', 2 => 'beg', 3 => 'bench', 4 => 'uniform', 5 => 'chalk', 6 => 'board', 7 => 'uniform' );
Now we are going to find the name of the array key where the value is “pen”. We can do it using array_search() PHP function. Below is how to do it:
$pen_key = array_search('pen', $arr); // $key = 1;
Similarly, we can get the key name for “chalk”:
$chalk_key = array_search('chalk', $arr); // $key = 5;
In the array, we can see that the value “uniform” is at the key 4 and also at the key 7. If we use the array_search() function to find the key name of “uniform”, then it will return the first array key 4.
$uniform_key = array_search('uniform', $arr); // $key = 4;