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.<?php
//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.
0 comments:
Post a Comment