In this tutorial, you shall learn how to get the last element in given array in PHP using array[index] notation and count() function, with the help of example programs.

PHP – Get last element in array

To get last element in array in PHP, we can use array index notation. Pass the length of array minus one as index to the array[index], and the expression returns the last element.

The expression to get the last element in array arr is

$arr[ count($arr) - 1 ]

Example

In this example, we take an array arr with some elements. We get the last element in the array and print it to output.

PHP Program

<?php
  $arr = ["apple", "banana", "cherry"];
  $last_element = $arr[ count($arr) - 1 ];
  echo $last_element;
?>

Output

PHP - Get last element in array
ADVERTISEMENT

Conclusion

In this PHP Tutorial, we learned how to get the last element in array using array indexing notation.