Get nth key of associative php array

jtubre picture jtubre · Apr 20, 2015 · Viewed 15.3k times · Source

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

Answer

Devon picture Devon · Apr 20, 2015

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