To get the last element in an array in PHP, you can use the end()
function.
In this example,
$numbers
with some elements.end()
function to get the last element of the array and store it in the variable $lastNumber
.$lastNumber
.<?php
$numbers = [1, 2, 3, 4, 5];
$lastNumber = end($numbers);
echo 'Last number is: ' . $lastNumber;
?>
Last number is: 5
In this example,
$fruits
with some elements.end()
function to get the last element of the array and store it in the variable $lastFruit
.$lastFruit
.<?php
$fruits = ['apple', 'banana', 'cherry'];
$lastFruit = end($fruits);
echo 'Last fruit is: ' . $lastFruit;
?>
Last fruit is: cherry
In this tutorial, we learned How to get Last Element in Array in PHP language with well detailed examples.