Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine and do stuff in foreach loop except the last iteration

Tags:

foreach

php

I am looping a foreach and i need to make some logic like this: if the iteration is not the last. Gather up the prices. when the iteration is the last. subtract from the total with the gathered up prices. except the last iteration price. I got the following code not. but it's not working.

    $i = 0;
    $credit = '';
    $count = count($reslist);

    foreach ($reslist as $single_reservation) {
            //All of the transactions to be settled by course
            //$credit             = $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');

            if ($i > $count && $single_reservation != end($reslist)) {
                $gather_sum_in_czk += $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
                $credit             = $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
            }
            //Last iteration need to subtract gathered up sum with total.
            else {
                $credit = $suminczk - $gather_sum_in_czk;
            }
    $i++;
    }

EDIT: TRYING TO GATHER UP PRICES FOR ALL INTERACTIONS EXECPT LAST:

          if ($i != $count - 1 || $i !== $count - 1) {
                $gather_sum_in_czk += $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
                $credit             = $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
            }

            else {
                $credit = $suminczk - $gather_sum_in_czk;
            }
like image 734
Prague2 Avatar asked Jan 17 '26 22:01

Prague2


1 Answers

The SPL CachingIterator is always one element behind its inner iterator. It can therefore report whether it will produce a next element via ->hasNext().
For the example I'm choosing a generator to demonstrate that this approach doesn't rely on any additional data like e.g. count($array).

<?php
// see http://docs.php.net/CachingIterator
//$cacheit = new CachingIterator( new ArrayIterator( range(1,10) ) );
$cacheit = new CachingIterator( gen_data() );

$sum = 0;                  
foreach($cacheit as $v) {
    if($cacheit->hasNext()) {
        $sum+= $v;
    }
    else {
        // ...and another operation for the last iteration
        $sum-=$v;
    }
}

echo $sum; // 1+2+3+4+5+6+7+8+9-10 = 35


// see http://docs.php.net/generators
function gen_data() {
    foreach( range(1,10) as $v ) {
        yield $v;
    }
}
like image 200
VolkerK Avatar answered Jan 19 '26 11:01

VolkerK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!