Reputation: 6799
I have retrieved some values from database. In my view file I have the following:
$row['fee_amount'];
Now, I want to sum up all the values inside $row['fee_amount']; and then show it.
I know I could sum up when querying the database, but I am interested to learn how to add using PHP .
Would you please kindly teach me how to do it?
<?php if(count($records) > 0) { ?>
<table id="table1" class="gtable sortable">
<thead>
<tr>
<th>S.N</th>
<th>Fee Type</th>
<th>Fee Amount</th>
</tr>
</thead>
<tbody>
<?php $i = 0; foreach ($records as $row){ $i++; ?>
<tr>
<td><?php echo $i; ?>.</td>
<td><?php echo $row['fee_type'];?></td>
<td><?php echo $row['fee_amount'];?></td>
</tr>
<?php } ?>
</tbody>
<tr>
<td></td>
<td>Total</td>
<td>
I WANT TO DISPLAY THE SUMMATION RESULT HERE ADDING UP VALUES INSIDE THIS>>> <? $row['fee_amount']; ?>
</td>
</tr>
</table>
<?php } ?>
Upvotes: 0
Views: 8974
Reputation: 197767
In your view file, with your foreach
loop, add a $sum
variable next to your $i
counter and add the amount per each iteration (similar to like you increase $i
):
<?php
$i = 0;
$sum = 0;
foreach ($records as $row)
{
$i++;
$sum += $row['fee_amount']; ?>
(I put this over multiple lines to make it more readable).
After the foreach
has finished, $sum
contains the total amount:
<td>Total: <?php echo $sum; ?></td>
That simple it is. You only need a new variable ($sum
) and do the calculation.
Upvotes: 3
Reputation: 9829
using this php function, if $row['fee_amount'] is an array ^_^
for example:
$a = array(2, 4, 6, 8);
array_sum($a)
Upvotes: 0
Reputation: 100175
You could use;
$someValue = 0; foreach($row["fee_amount"] as $value) { $someValue = $someValue + $value; }
Upvotes: 0
Reputation: 17762
Use a loop
$sum = 0;
while($row...){
$sum += $row['fee_amount']
}
echo $sum;
Upvotes: 2