user850234
user850234

Reputation: 3463

How to use loop within foreach in php to add numbers

I am using php and have the following structure

<?php if(!empty($bids)): ?>
  <?php foreach ($bids as $bid):?>
     <tr>
         <td><?php if($bid['Bid']['debit'] > 0) : ?><?php echo $bid['Bid']['debit']; ?><?php else: ?>&nbsp;<?php endif; ?></td>
         <td><?php if($bid['Bid']['credit'] > 0) : ?><?php echo $bid['Bid']['credit']; ?><?php else: ?>&nbsp;<?php endif; ?></td>
     </tr>
  <?php endforeach; ?>
<?php endif;?>

Now i need to calculate the sum total in each case. I know its easy but not getting how to use loop within the foreach to calculate the total value. Please suggest how to do that loop.

If suppose for the first td sample output structrue is as like below, i need to add up all and just display 22 and not the array

0 2 0 20

Upvotes: 1

Views: 1964

Answers (3)

Md Jawed Shamshedi
Md Jawed Shamshedi

Reputation: 314

It's better to define variable inside the loop and add values to the variable and then print the variable.

Upvotes: 0

SERPRO
SERPRO

Reputation: 10067

Why don't you add a counter variable outside the foreach?

  <?php
  $total['debit'] = 0;
  $total['credit'] = 0;
  foreach ((array)$bids as $bid)
  {
     $debit = ($bid['Bid']['debit'] > 0)? $bid['Bid']['debit'] : 0;
     $credit = ($bid['Bid']['credit'] > 0)? $bid['Bid']['credit'] : 0;
     $total['debit'] += $debit;
     $total['credit'] += $credit;
     $output =<<<XHTML
     <tr>
         <td>{$debit}</td>
         <td>{$credit}</td>
     </tr>
  XHTML;
     echo $output;
  }
  ?>

Upvotes: 1

hsz
hsz

Reputation: 152216

Try with:

<?php

if(!empty($bids)) {
  $debitSum  = 0;
  $creditSum = 0;

  foreach ($bids as $bid) {
    $debit  = $bid['Bid']['debit'];
    $credit = $bid['Bid']['credit'];

    echo '<tr>';
    echo '<td>' . ( $debit > 0 ? $debit  : '&nbsp;' ) . '</td>';
    echo '<td>' . ( $credit> 0 ? $credit : '&nbsp;' ) . '</td>';
    echo '</tr>';

    $debitSum  += $debit;
    $creditSum += $credit;
  }

  echo '<tr style="font-weight: bold">';
  echo '<td>' . $debitSum . '</td>';
  echo '<td>' . $creditSum . '</td>';
  echo '</tr>';

}
?>

Edit:

If $bid['Bid']['debit'] (or credit too) is a string value, then cast it to int value:

$debit = (int) $bid['Bid']['debit'];

Upvotes: 4

Related Questions