To determine the key of an array by knowing its value, there are at least three possible solutions:
- You can use the well-known array_search function. We already used it earlier in the article on removing an element from an array.
- Use a loop to iterate through all elements of the array and compare values to identify the key.
- Use the array_walk function, imitating option 2.
Initial data:
<?php $array = [
10 => 'Lorem',
12 => 'Ipsum',
15 => 'simply',
20 => 'dummy',
33 => 'text',
];Above is an array where both keys and values are unique. Note: if your values are not unique, the returned key will be for the first matching element.
Example 1
Here we use PHP's array_search function to find the key of the value "simply":
<?php //Example 1 $search_value = 'simply'; echo var_dump(array_search($search_value, $array)); echo "n";
The result will be — int(15)
Example 2
We use a foreach loop to go through the array and an if-statement to compare values:
<?php //Example 2
$search_value = 'Ipsum';
foreach( $array as $key => $value )
{
if($search_value == $value)
{
var_dump($key);
echo "\n";
break;
}
}For the value "Ipsum", the result will be the key "int(12)"
Example 3
Probably the longest and weirdest method is using array_walk and passing the $search_key by reference through use:
<?php
//Example 3
$search_value = 'Lorem';
$search_key = NULL;
array_walk($array, function($value, $key, $search_value) use(&$search_key){
if($search_value == $value)
{
$search_key = $key;
}
}, $search_value);
var_dump($search_key);The result will be either NULL (if not found), or int(10) if the value "Lorem" is found.
So, what’s the conclusion? Don’t overthink it — just use what’s already built into PHP, namely the ready-made array_search function.
Earlier, at the beginning of my PHP programming journey, I often wrote such "bicycles" like in examples 2 and 3. Over time, I got smarter and started checking the PHP docs to see if something already existed. And now, with platforms like GitHub, development speed can be increased even more. Good luck!
