dukevin
dukevin

Reputation: 23178

PHP return array key

I have an array $food like:

Array
(
    [apple] => Array
        (
            [color] => red
            [type] => fruit
        )

    [choco] => Array
        (
            [color] => brown
            [type] => candy
        )

)

Is there a function where I can do:

get_key($food, 0) and it would return index 0, apple

get_key($food, 1) returns choco

Upvotes: 1

Views: 689

Answers (2)

Oussama Jilal
Oussama Jilal

Reputation: 7739

You can do this :

$keys = array_keys($array);

echo $keys[0];
echo $keys[1];

Upvotes: 7

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

function get_key($array, $index) {
    $allItems = array_keys($array);
    $selectedItem = $allItems[$index];
    return $selectedItem;
}

Upvotes: 5

Related Questions