Accessing the first element in associative PHP array

Accessing the first element in a php array can be done as easy as this

$myArray[0] = 'foo';

and you can also use “list” to access more than one index in one call

list( $first, $second, $third ) = $myArray;

This approach , however, doesn’t work with associative arrays or arrays that have non-standard integer index like

$stringIndexedArray = array('first' => 'data','second' => 'data');
$nonStandardIntegerIndexedArray = array(5 => 'foo', 7=>'bar');

I have found two methods to access the first element in such arrays, one using “reset” and the other using “array_values

$stringIndexedArray= 
array(
	'first'  => 'Data 1',
	'second' => 'Data 2',
	'third'  => 'Data 3',
	'forth'  => 'Data 4',
	'fifth'  => 'Data 5'
);
//reset method
//Average execution time : 2.8123000000003E-6
$firstElement = reset($stringIndexedArray);
 
//array_values method
//Average execution time : 3.8123000000001E-6
list($firstElement) = array_values( $stringIndexedArray );

I’ve done some profiling and turns out that “reset” method is slightly faster than “array_values” ( as seen in code comments )



2 Responses to “Accessing the first element in associative PHP array”

  1. PHP Array says:

    If you dont mind removing the element off the array, you can also use array_shift()

  2. مصطفى says:

    Hmmm, Didn’t use array_shift() before, Looks like reversed array_pop(), Thanks for the comment :)

Leave a Reply