Practical Web Programming

Friday, January 30, 2009

PHP: How to Get the Last Element of an Array

If you know it's length, getting the last element of an array is easy. You just put the index of the last element and you have it's value. But what if you don't know it's length or your array is populated at runtime and it's length is dynamic? Now you got a problem :).

To solve this, you also need a dynamic approach. Using PHP's count function, you can dynamically get the last element of an array. Here's how.


//Getting the last element of an array dynamically

$arr = array("one", "two", "three", "four", "five");
print "Last element: " . $arr[count($arr) -1];


Take note that in PHP, arrays starts at 0, so if you have five elements, the index of the first element is 0 and the last's is 4. So the code count($arr) will return 5, while count($arr) - 1 will return 4.


Recent Post