2

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.

Pankit Kapadia
  • 1,579
  • 13
  • 25
undefined
  • 2,051
  • 3
  • 26
  • 47

4 Answers4

2

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++;
}
?>
Pankit Kapadia
  • 1,579
  • 13
  • 25
2

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);  
    }  
}
DiverseAndRemote.com
  • 19,314
  • 10
  • 61
  • 70
1

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
brunoais
  • 6,258
  • 8
  • 39
  • 59
0

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.

Alexander Guz
  • 1,334
  • 12
  • 31