PHP: Get the first element of an associative array.

This is a small tutorial on how to get the first element of an associative array in PHP. As you probably already know, associative arrays are extremely popular in PHP, simply because they allow you to set keys / indexes that are human-friendly! Unfortunately, one of the drawbacks to using an associative array is that it can be difficult to retrieve elements based on their position!

Getting the first element is pretty easy if you understand the reset function. This function allows you to “reset” the internal pointer of an array back to its first element:

<?php

//Example associative array.
$array = array(
    'first_key' => 'Example #1',
    'second_key' => 'Example #2',
    'third_key' => 'Example #3'
);

//Use the reset function to "set the internal pointer of an array to its first element".
//i.e. Reset it back to the start.
$firstElement = reset($array);

//var_dump the result for illustrative purposes.
echo $firstElement;

If you run the code snippet above, you’ll see that the reset function returns the first element of an array, regardless of whether it is an associative array or not.

Getting the first key of an associative array.

This is another common problem that developers face when working with associative arrays. When working with numbered indexes, it is pretty safe to assume that the first key will be “0”. However, with an associative array, it isn’t that easy.

<?php

//The same example array.
$array = array(
    'first_key' => 'Example',
    'second_key' => 'Example #2',
    'third_key' => 'Example #3'
);

//Reset the array back to the start.
reset($array);

//Fetch the key from the current element.
$key = key($array);

In the example above, we combined the reset function and the key function in order to get the first key of our array.

Related: Get the LAST element of an associative array.