K20GH
K20GH

Reputation: 6263

How to get last value of for loop?

I'm trying to get the value of $row->price for the last iteration in my for loop as below

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

I did try the following, however it didn't appear to work

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

Any suggestions?

Upvotes: 1

Views: 4388

Answers (3)

Kevin Choppin
Kevin Choppin

Reputation: 394

You can use php end to get the last value of an array.

eg;

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

Upvotes: 1

Floris
Floris

Reputation: 46375

Add a line $lastitem=$row right after the for statement ; it will contain the last value after the loop is finished

Upvotes: 1

Jon
Jon

Reputation: 437376

Use $row->price just after the loop has ended:

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

$lastprice = $row->price;

This is really just a trick, but it will work. If you are iterating over an array you can also do it like this:

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

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

Upvotes: 3

Related Questions