![]() The end() function will move the pointer to the last element in the array and return the value of it. ![]() There are a few PHP functions that deal with moving this pointer around an array, but for the purposes of finding the first and last element we only need to look at current(), reset(), and end(). ![]() When the array is created this pointer is initialised to be the first element in the array. Every array has an internal pointer that points to the 'current' element. However, the best way to extract the first and last items from an array is by using the internal PHP array pointer functions. There are clearly a few ways of doing this simple task in PHP. Print array_pop($array_values) // prints 'three'Īnother way that is similar to this would to use the array_keys() function to return the first and last keys of the array using array_shift() and array_pop(), which would then be referenced directly within the original array. Print array_shift($array_values) // prints 'one' This provides us with an easy mechanism to complete our original task without these functions altering the original array. The array_pop() function takes an array as it's only parameter and will cut off and return the last item found in the array. The array_shift() function takes an array as it's only parameter and will cut off and return the first item found in that array. Print $array_values // prints 'three'Īs the array_values() function creates returns a copy of the array we can use the a couple of functions to snip off the beginning and end of the array without altering the original array. Therefore, you can just use the original method to find the first and last items. This means that the first item in the array will have a key of 0 and the last item will have a key of the length of the array, minus 1. One way of doing this is to use the array_values() function, which will return an array with all of the key values reset. PHP comes with a couple of functions that can help when pulling out items in an array. Also, if we try to access the last item in the array in the same way as before then we will return the value 'two' as the length of the array (3) minus 1 will point to the key in the middle of this array. It isn't possible to reference the first item of the array as 0 here because that array key doesn't exist (we would get an 'undefined offset' error in this case). To get the last item in the array the index key will be the length of the array, minus 1. This means that in order to get the first element from an array you just reference the default starting position (0). If you create an array and then add a bunch of values to it then the array index will increment by 1 for every element you add. Getting the first or last item from an array in PHP is usually quite easy.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |