Primary links
Get last element of an array
We all know that array_pop, pops and returns the last value of the array. But it also shortens the length of the array by one. So how do we get the last element of an array without shortening it. We can always loop thru the array and get the last element. But this is not a good practice.
We could also use [sizeof($array) - 1] . But you can go wrong. Say you unset a middle element, PHP does not reindex the remaining elements. For example, the following code will produce an Undefined offset notice:
$arr = array('a', 'b', 'c');
unset($arr[1]);
echo $arr[count($arr)-1];
So how do we get the alst element without an error or notice, without shortening the array and without consuming too much resources ? Use the simple functions below ...
$myLastElement = end($yourArray);
end sets the internal pointer of an array to its last element.
But after this , make sure you reset the array pointer using reset($your_array).
User login
Follow Us
Who's online
Who's new
- Nisha
- linnaeus
- Yameen
- TalleyReedy
- admin

