a coder
a coder

Reputation: 7659

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

Upvotes: 0

Views: 985

Answers (3)

micster
micster

Reputation: 758

You can use array_keys() function:

function getKey($arr, $i) {
    if (empty($arr[array_keys($arr)[$i]])) {
        return null;
    }

    // array_keys($arr)[$i] returns original array's key at i position
    // if i = 2, array_keys($arr)[$i] = 'product3'
    return array_keys($arr)[$i];
}

// echo getKey($arr, 2);
// returns product3

Upvotes: 1

mickmackusa
mickmackusa

Reputation: 47992

It doesn't seem logical/efficient to generate a new/full array of keys just to select one from it. The other answers are "working too hard".

array_slice() specifically extracts portions of an array based on position rather than key name. This makes it the perfect function for this case.

Better practice would be to only slice away the subarray that you want, then call for its key, like this:

Code: (Demo)

$arr = array(
            'product1'=>array('color'=>'blue','size'=>'medium'),
            'product2'=>array('color'=>'green','size'=>'large'),
            'product3'=>array('color'=>'yellow','size'=>'small'),
        );
$key=2;
echo key(array_slice($arr,$key,1));  // [input],[0-indexed position],[number of subarrays]

Output:

product3

Upvotes: 2

Vincent Decaux
Vincent Decaux

Reputation: 10714

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

Upvotes: 3

Related Questions