Smiley Happy Coder

Lyle Barras

Lyle is Smiley Happy Coder

Developing for the web since 1999, that's 16 years

Get the first element in an array using PHP reset

PHP Reset
In my last post we discovered how to find the last element in an array by using the end() function. This is brilliant and no doubt going to help you out on a regular basis. But now we’ve set the pointer to the end of the array, how do we get it back to the start?

We use the reset function of course!

The reset function can be used like this
$things = [ 'bat' , 'sponge' , 'cabbage' ];
//Lets just jump to the end of the array for the fun of it.
end( $things );
echo reset( $things); //Will echo "bat"

Now you might be thinking, “Why the heck do I need to remember this function, when I can just call the 0 index?”

I have to admit I totally agree, surely something like this is exactly the same thing?
echo $things[0];

Anyone any thoughts as to why reset is better if, in fact, it is?


Thanks to @olimortimer for highlighting a couple of bugs, now been fixed.

@WarpcodeUk also suggested that this would be a viable answer to handle associative arrays. Using reset() in this case would simply return the first array.

$things_values = array_values($things); echo $things_values[0];

Thanks very much to both.

  • Top