This is a short guide on how to get the last element (or key) of an associative array in PHP. Note that we will do this without having to loop through the entire array (a wasteful process, I think you’ll agree).
For this tutorial, I’m going to use the following associative array as an example:
As you can see, it’s just a simple associative array with three elements. The last element, which has the index “random”, contains the string “Hi”.
To get the last element, we are going to use the PHP function end, which changes the internal pointer of an array to its last element:
Simple!
But what if we want to get the key / index of the last element? Well, it’s kind of similar:
As you can see, using the end function and the key function is a lot less wasteful than looping over the entire array!
0 comments:
Post a Comment