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];
Related videos on Youtube
Author by
jtubre
Updated on June 06, 2022Comments
-
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 about 9 yearsThanks. 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 almost 6 yearsGah, i've been screwing around with reset(array) then key(array), this method is a lot easier. Simple thing overlooked.
-
FrancescoMM over 3 yearsarray_keys will generate a full copy of all the keys. Very inefficient on long arrays.
-
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 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 about 2 yearsThank You. It works perfectly in my case.