Retrieve the last element in PHP
In PHP, to get the last element from an array, first, you need to count the total array elements
$languages = [ 'JAVA', 'PHP', 'C++', 'C#', 'Python', ]; $totalElements = count($languages); echo $languages[$totalElements - 1];
- Above code will output
Pythoni.e the last element in a provided array.
- It is a more readable approach, can also be rewritten in a single line as shown, which sometimes looks complex for beginners.
echo $languages[count($languages) - 1];