29

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]);

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
jtubre
  • 669
  • 1
  • 8
  • 13
  • That's a very unusual requirement for an **associative** array. – Devon Bessemer Apr 20 '15 at 00:41
  • Question shown as duplicate http://stackoverflow.com/questions/4769148/accessing-an-associative-array-by-integer-index-in-php is not the same. He's wants to set a value based on index, I'm needing to reference the key value based on index. – jtubre Apr 20 '15 at 15:46

1 Answers1

56

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];
Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • 2
    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. – jtubre Apr 20 '15 at 00:49
  • Gah, i've been screwing around with reset(array) then key(array), this method is a lot easier. Simple thing overlooked. – Solvision May 21 '18 at 20:51
  • array_keys will generate a full copy of all the keys. Very inefficient on long arrays. – FrancescoMM Nov 03 '20 at 12:04
  • @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 Bessemer Nov 03 '20 at 14:37
  • @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. – Devon Bessemer Nov 04 '20 at 20:13