如何获取for循环的最后一个值?

时间:2013-05-18 23:28:47

标签: php

我正在尝试获取for循环中最后一次迭代的$ row->价格值,如下所示

foreach ($getprices->result() as $row)
{
    if ($bb=='on'){
        $pric = $row->price+2.50;
        $pri = number_format($pric,2);
    }else{
        $pric = $row->price;
        $pri = number_format($pric,2);
    }

我确实尝试了以下操作,但它似乎无法正常工作

$numItems = count($getprices->result());
$i = 0;
foreach($getprices->result() as $row) {
  if(++$i === $numItems) {
    if ($bb=='on'){
        $pric = $row->price+2.50;
        $pri = number_format($pric,2);
    }else{
        $pric = $row->price;
        $pri = number_format($pric,2);
    }
  }
} 

有什么建议吗?

3 个答案:

答案 0 :(得分:3)

在循环结束后立即使用$row->price

foreach ($getprices->result() as $row)
{
    // ...
}

$lastprice = $row->price;

这真的只是一个技巧,但它会起作用。如果你在迭代一个数组,你也可以这样做:

$array = $getprices->result();
foreach ($array as $row)
{
    // ...
}

$lastprice = end($array)->price; // this will work independently of any loop

答案 1 :(得分:1)

在for语句后面添加一行$lastitem=$row;它将包含循环结束后的最后一个值

答案 2 :(得分:1)

您可以使用php end获取数组的最后一个值。

例如

$arr = $getprices->result();
$last = end($arr);