find the last element in an array in php

To find the last element in an array in PHP, you can use the end() function. This function moves the internal pointer of an array to its last element and returns that element.

main.php
$array = array('apple', 'banana', 'orange');
$last_element = end($array);
echo $last_element; // Output: orange
112 chars
4 lines

Alternatively, you can use the count() function to get the total number of elements in the array and subtract 1 to get the index of the last element.

main.php
$array = array('apple', 'banana', 'orange');
$last_element = $array[count($array)-1];
echo $last_element; // Output: orange
124 chars
4 lines

related categories

gistlibby LogSnag