Get nth key of associative php array

18,097

array_keys produces a numerical array of an array's keys.

$keys = array_keys($array);
$key = $keys[1];

If you're using PHP 5.4 or above, you can use a short-hand notation:

$key = array_keys($array)[1];
Share:
18,097

Related videos on Youtube

jtubre
Author by

jtubre

Updated on June 06, 2022

Comments

  • jtubre
    jtubre almost 2 years

    I want to get the value of the KEY of an associative PHP array at a specific entry. Specifically, I know the KEY I need is the key to the second entry in the array.

    Example:

    $array = array('customer' => 'Joe', 'phone' => '555-555-5555');
    

    What I'm building is super-dynamic, so I do NOT know the second entry will be 'phone'. Is there an easy way to grab it?

    In short, (I know it doesn't work, but...) I'm looking for something functionally equivalent to: key($array[1]);

  • jtubre
    jtubre about 9 years
    Thanks. Especially for the second line. Was not aware of this shortcut. It works but unfortunately, my DW CS5.5 error checking doesn't like it.
  • Solvision
    Solvision almost 6 years
    Gah, i've been screwing around with reset(array) then key(array), this method is a lot easier. Simple thing overlooked.
  • FrancescoMM
    FrancescoMM over 3 years
    array_keys will generate a full copy of all the keys. Very inefficient on long arrays.
  • Devon
    Devon over 3 years
    @FrancescoMM, do you have a very long associative array? that's probably a code smell. The other alternative is iterating through your array, but if you actually want to reference your associative array by integers, you would need to create a new structure.
  • Devon
    Devon over 3 years
    @FrancescoMM I'm not following you, where did reversing the array come from? Generally speaking, an associative array is a hash table, it's ideal for indexing but not ordering. If you have a new problem than the one listed here, feel free to link to your question, but I would recommend making sure you're using the right data structure in the first place.
  • LUISAO
    LUISAO about 2 years
    Thank You. It works perfectly in my case.