How can I get the last element of an array without changing its internal pointer?
What i'm doing is:
while(list($key, $value) = each($array)) {
//do stuff
if($condition) {
//Here I want to check if this is the last element of the array
prev($array);
}
}
so end($array)
would mess things up.
It's simple, you could use:
$lastElementKey = end(array_keys($array));
while(list($key, $value) = each($array)) {
//do stuff
if($key == $lastElementKey) {
//Here I want to check if this is the last element of the array
prev($array);
}
}
Try this:
<?php
$array=array(1,2,3,4,5);
$totalelements = count($array);
$count=1;
while(list($key, $value) = each($array)) {
//do stuff
if($count == $totalelements){ //check here if it is last element
echo $value;
}
$count++;
}
?>
Something like this:
$array = array_reverse($array, true);
$l = each($array);
$lastKey = $l['key'];
$array = array_reverse($array, true);
while(list($key, $value) = each($array)) {
//do stuff
if($key == $lastKey) {
echo $key . ' ' . $value . PHP_EOL;
}
}
The problem here is that if the array is big one then it'll take some time to reverse it.
Why not just using something like:
$lastElement= end($array);
reset($array);
while(list($key, $value) = each($array)) {
//do stuff
}
// Do the extra stuff for the last element