Divide current value with previous value of an array inside a foreach loop in Codeigniter


How do I divide the current value with previous value to get growth or shortage percentage in an array of foreach loop in Codeigniter.

My model is:

public function get_monthly_collection() {    
    $sql = 'SELECT p.*,
          , SUM(CASE WHEN `category` = 2 THEN amount END) AS reg
          , SUM(CASE WHEN `category` = 3 THEN amount END) AS rec
          , SUM(CASE WHEN `category` = 4 THEN amount END) AS blk
          , SUM(CASE WHEN `category` = 5 THEN amount END) AS leg
      FROM mcl_transactions t
      LEFT JOIN projects p ON p.title = t.mcl_no 
      WHERE p.project_no = 1 AND t.trnx_date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
      GROUP BY t.trnx_date
      ORDER BY t.trnx_date DESC';
    $query = $this->db->query($sql);
    if ($query->num_rows() > 0) {
      return $query->result();
    } else {
      return null;

My View File looks like:

<div class="col-md-12">
    <div class="card">
      <div class="card-body p-3">
        <div class="row">
          <?php $reg_coll = $this->Project_model->get_monthly_reg_coll();?>
          <?php foreach($reg_coll as $coll) { ?>
          <div class="col-md-4">
            <table style="font-size:12px" class="table table-sm table-bordered border-primary text-center">
                <td class="text-primary" colspan="4"><?php echo DATE('d-M D',strtotime($coll->trnx_date)); ?></td>
              <tr class="bg-primary text-white">
                <td><?php echo number_format($coll->reg,0);?></td>
                <td><?php echo number_format($coll->rec,0);?></td>
                <td><?php echo number_format($coll->blk,0);?></td>
                <td><?php echo number_format($coll->leg,0);?></td>
                <td colspan="4"><?php echo 'Divide Current Value with Previous Value'; ?></td>
          <?php } ?>

Inside the last table cell I want to divide second index value with first index value to know if the collection amount is improving or decreasing. How can I achieve this. Thanks in advance.

>Solution :

If I’m understanding you correctly you’re looking to run a calculation based on the previous $coll ?

For that you can store the previous in a variable at the end of a loop, that way it can be referenced on the next item.

        <?php $previousValue = null; ?>
        foreach($reg_coll as $coll){
            // ... Other stuff here
            if($previousValue !== null){
                echo $coll->value / $previousValue;
            $previousValue = $coll->value;

Leave a Reply Cancel reply