PHP: Get the data of a first array

Hey everyone,

I have a question regarding array in PHP. How do you get the data array of the first element of an array when the keys are unknown.

array (
	
	[???] => array(
			'id' => 50,
			'name' => 'John',
			'email' => 'jogn@example.com'
	
	),
	[???] => array(
			'id' => 56,
			'name' => 'Pony',
			'email' => 'pony@example.com'
	
	)


);

Thanks

The array_keys() function is the best function i can see that you could use.

Arrays have an internal pointer, much akin to how a file pointer works. Just reset the array and read the current one. In fact, the reset command when done on an array returns the first record.

$firstRecord=reset($yourArray);

Relevant commands you should read up on:
PHP: reset - Manual
PHP: next - Manual
PHP: prev - Manual
PHP: end - Manual
PHP: each - Manual
PHP: current - Manual

The ‘foreach’ construct actually performs a reset() when it starts, then does a bunch of each().

@deathshadow60,

If I use the reset() function, will it not destroy my current keys?

reset has nothing to do with keys – the internal pointer is used for iterating the array, not for populating it. Its no different than performing a foreach on it.


reset($myarray);
while ( list($key,$data)=each($myarray) ) {
  /* do something here */
}

is functionally identical to:


foreach ($myarray as $key => $data) {
  /* do something here */
}

Though nowhere near as elegant. NONE of those commands change the contents of the array or it’s length or keys or anything else. The only thing that’s changed is the internal read pointer… READ pointer.

So for example if you want the first record of the array and it’s key…

$firstRecord=reset($myarray);
$firstKey=key($myarray);

Doesn’t change the array’s values at all.

NOTE do not try to use those functions inside foreach though – foreach uses that same internal read pointer.

Thank u so much deathshadow60 for the deatailed explanation.