Developing for the web since 1999, that's 16 years
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?
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;
Thanks very much to both.