PHP: Best way to get the first element of an array

2014-03-19 2018-04-22 12:30:18 PHP,Snippets,EN

Q: how to determine the value of the first element of an array if the key is unknown ?

A: make use of the reset command to set the array pointer back to start and to get the value of the array's first element.

// associative array
$aArray = array(
    'foo' => 'bar', 
    'john' => 'doe'
);

// value of array's first element
$mValue = reset($aArray); // bar

// key of array's first element
$mKey = key(reset($aArray)); // foo

// value of array's first element
$mValue = $aArray[key(reset($aArray))]; // bar

This website uses Cookies to provide you with the best possible service. Please see our Privacy Policy for more information. Click the check box below to accept cookies. Then confirm with a click on "Save".