PHP search array key by value in array

Hello guys

While working with PHP array, you may want to search array key by value. PHP has array_search function to search value from array and return its key.

<?php

$arr = array('red' => 'apple', 'orange' => 'mango', 'yello' => 'banana');

$key = array_search('mango', $arr); // orange
echo($key);

The second option is to flip the array and then search it. array_flip function will flip key and value in the array.

<?php

$arr = array('red' => 'apple', 'orange' => 'mango', 'yello' => 'banana');

$arr = array_flip($arr);
echo($arr['mango']);

The third option is loop through array and search for the key for specific value.

<?php

$arr = array('red' => 'apple', 'orange' => 'mango', 'yello' => 'banana');

foreach($arr as $key => $value) {
    if ($value == 'mango') {
        echo($key);
    }
}

Looping array to search for key is not good option if the array length is long.

I hope it will help you.

Tags: