获取数组的最后一个元素,而不更改其内部指针

时间:2012-12-15 09:43:52

标签: php arrays

如何在不更改内部指针的情况下获取数组的最后一个元素?

我在做的是:

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);  
    }  
}

所以end($array)会搞砸。

4 个答案:

答案 0 :(得分:2)

试试这个:

<?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++;
}
?>

答案 1 :(得分:2)

这很简单,你可以使用:

$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);  
    }  
}

答案 2 :(得分:1)

为什么不使用以下内容:

$lastElement= end($array);
reset($array);
while(list($key, $value) = each($array)) {  
    //do stuff   
}

// Do the extra stuff for the last element

答案 3 :(得分:0)

这样的事情:

$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;
    }  
}

这里的问题是,如果阵列很大,那么它需要一些时间来逆转它。

相关问题