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: Simple Method to Implode or Explode Arrays with Keys CodeUnit 21 NOV 2011

Associative arrays are very useful beasts, because values tied to keys makes it so much easier to build up pseudo objects in that it makes it easier to see which piece of array data refers to what.

There are a number of ways to store associative arrays of course, but this particular one below is probably one of the simplest for getting a single string out of a one level array with keys, and then transforming back into its array form when you need to make use of it again.

function array_implode_with_keys($array){
    $return = '';
    if (count($array) > 0){
    foreach ($array as $key=>$value){
    $return .= $key . '||||' . $value . '----';
    }
    $return = substr($return,0,strlen($return) - 4);
    }
    return $return;
}

function array_explode_with_keys($string){
    $return = array();
    $pieces = explode('----',$string);
    foreach($pieces as $piece){
        $keyval = explode('||||',$piece);
        if (count($keyval) > 1){
        $return[$keyval[0]] = $keyval[1];
        } else {
        $return[$keyval[0]] = '';
        }
    }
    return $return;
}

If you look at the code above, you will see that we are making use of delimiters here to keep firstly the keys aparts, and secondly the key from its associated value. In this case we are using —- to split the array elements, and |||| to split the key from its value.

In other words the resulting string is from the implode function is key1||||value1—-key2||||value2—-key3||||value3.

Obviously the explode function just works in reverse.