PHP Array Last Element / Value Examples
At one point of time or the other, you may have worked with a very important concept in PHP, called “Arrays”. There are simpler ways to get the first element of an array. But do you know how to get array last element, or get last value from array using PHP especially when that array is a dynamic array? In this article, I am going to explain how to use PHP to get array last element. This procedure applies both to an array that has a limited set of values and to an array in which, the set of values are unknown. Read on to find out more.
Examples to Get Array Last Value / Element using PHP
For the sake of the example, let’s assume that we have an array that contains fruits names. So let’s see how the array basically can look like:
$fruits_array = array('apple', 'mango', 'grapes');Example #1: Access Array First Element
//The following gives us 'apple' echo $fruits_array[0];
Example #2: Access Array Last Element when the number of values is known:
Since we know that the above array consists of a finite number of values i.e. 3, we can access the last array element i.e. the value ‘grapes’ by using the following code:
//The following gives us 'grapes' echo $fruits_array[2];
So far, so good? Now let’s assume that this array is now dynamic. This means that we perform some operation on the array and we keep adding values to array. In such an instance, it would not be feasible to manually count all the values inside the array and then apply our above solution to get the last array value. In such a case, we can easily get array last element for a dynamic array by using the following code:
//The following gives us 'grapes' echo end($fruits_array);
So simply use the end() function to get array last element.
Example #3: PHP Get Array Last Element Index
Well, we know now how to get the last value from a dynamic array. Wouldn’t that be good to know how to get array last element index? So let’s do it. We will go ahead & find array last value’s index. This can be done as:
$last_element_key = array_pop(array_keys($fruits_array)); echo $last_element_key;
Simple, isn’t it?
Do you know of any other ways to get array last item using PHP? Feel free to suggest by commenting below.