a coder a coder - 1 year ago 64
PHP Question

How to get key of an associative array by searching for offset value?

Using this as an example and being aware of key,

$arr = array(
'product1'=>array('color'=>'blue','size'=>'medium'),
'product2'=>array('color'=>'green','size'=>'large'),
'product3'=>array('color'=>'yellow','size'=>'small'),
);


Is there a method for getting any key in multidimensional array by its incremented value?

For example, I'd like to get the key of the third array value in
$arr
above.
$arr[2]
would return the value (an array containing yellow/small).

Is there a way to leverage the
key
function to get any key by its numeric iterator, rather than the key from the "current position"?

Or, is there another built-in function that I am obviously overlooking which would return the key of
$arr[2]
instead of it's value?

echo getkey($arr[2]);

# returns product3

Answer Source

Just use array_keys function :

$arr = array(
            'product1'=>array('color'=>'blue','size'=>'medium'),
            'product2'=>array('color'=>'green','size'=>'large'),
            'product3'=>array('color'=>'yellow','size'=>'small'),
        );

$keys = array_keys($arr);

echo $keys[2];

// shorter version
echo array_keys($arr)[2];

More infos : http://php.net/manual/en/function.array-keys.php

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download