At first sight this question seems like a trivial one – “how to get the first element’s value in a PHP array?”. Most people would answer with:

  $firstElem = reset($array);

This will work for 90% of the cases, but is not a possible approach every time for the following reason:

reset() rewinds array’s internal pointer to the first element and returns the value of the first array element. from the PHP documentation for reset()

So forget about using current() and next() on that array if you use reset() on it.

To overcome this pitfall, we can use a different approch:

function getFirstElem(array $arr){
    return array_shift(array_values($arr))
}

$firstElem = getFirstElem($myArray);

This will make a copy of the array’s values and get the first element from that copy. Using this approach your internal pointers to $myArray will not be lost.

(Image credit by “Andre Chinn”)

Leave a Reply

Your email address will not be published. Required fields are marked *