Tag Archives: internal pointer

PHP: Get the first Key of an Associative Array Tips, Tricks and Tutorials 16 JUN 2018

I am not completely sure about it, but I somehow don’t think that I’ve ever needed to get the first key of an associative array using PHP before. Sure, a simple problem with a simple solution, but seeing as I needed to Google this one, I’m jotting down the answer here for future reference.

So, our example for the day then: Given the following array, print out the first key.

$months = array(
'jan'=>'January',
'feb'=>'February',
'mar'=>'March',
'apr'=>'April',
'may'=>'May',
'jun'=>'June',
'jul'=>'July',
'aug'=>'August',
'sep'=>'September',
'oct'=>'October',
'nov'=>'November',
'dec'=>'December'
);

reset($months);
$result = key($months);
if ($result !== NULL){
echo $result; //this will print 'jan'
}

The important bits are reset(), which moves the internal array pointer back to the first element of the array, and then key(), which retrieves the index element at the current array position (dictated by the internal pointer).

Simple (when you read the documentation).

UPDATE: As pointed out by one of my readers, if you know you have an array with at least one element in it, you could always just use array_keys($months)[0] as an alternative.

Related Link: reset() | key()