Tag Archives: array_keys

PHP: How to Get the Associated Key from an Array given a Value Programming 06 FEB 2012

If you have a value and you suspect that it might be contained within your array, can you somehow find the key linked to that value if it does exist?

The answer is yes, thanks to the handy array_search function which searches an array for a given value and returns the corresponding key if the search is successful, and false if the value isn’t found in the array.

In practice:

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;

(Note that similar to strpos validations, you need to make use of the === operator when testing the return value of this function).

The array_search returns the first match it comes across, meaning that if the value is in the array, you’ll only know of one instance. If it is important to know all of the corresponding keys where the value can be found, rather use the array_keys function, but this time with the optional search parameter.

In practice:

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
/*
returns:
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
*/

Useful.

PHP: How to Create a Single String of Array Keys using Implode CodeUnit 09 NOV 2011

PHP’s implode function is extremely useful for flattening a one dimensional array into a string. This time around, we want to create a flat string of an array’s keys, ignoring the actual values for a change.

To achieve this is actually very simple – it’s just a matter of combining the stock standard array_keys() and implode() functions together!

So given an array that looks like this:

$myarray = array('green'=>'leaf','blue'=>'sky','red'=>'apple');

We can get a flattened string reading green||blue||red by doing the following:

echo implode('||',array_keys($myarray));

Simple. The array_keys function first returns an array containing the keys of our aforementioned array, before the implode function flattens it using || as a delimiter.

Nifty.