faza
faza

Reputation: 257

sum all value in foreach loop php

 <?php  foreach((array)$query as $row):?>
  <td><?php echo $row->date ?></td>
  <td><?php echo $row->cost ?></td>
  <?php endforeach ;?>

I want to sum all values in $row->cost when $row->date=02-01-2016, like this in a table enter image description here

Thanks.

Upvotes: 0

Views: 4185

Answers (4)

Nitesh Pawar
Nitesh Pawar

Reputation: 425

<table border=1>
<?php
$tot = 0;
foreach($query as $row ) {
    if( $row->date=='2016-01-02' ) $tot += $row->cost;
?>
<tr>
<td><?php echo $row->date ?></td>
<td><?php echo $row->cost ?></td>
</tr>
<?php } ?>
<tr><td></td><td><?php echo $total; ?></td></tr>
</table>

It will work for you exctly what u want.

Upvotes: 0

kamal pal
kamal pal

Reputation: 4207

echo array_sum(array_filter(array_map(function($row){
  if($row->date == '02-01-2016')
    return $row->cost;
}, $array))); 

You can use

  • array_map: to compare and skip the values for which cost is not needed to add in sum.
  • array_filter: and then to remove the blank indexes
  • array_sum: and finally to sum cost

Note: if you are getting results from database, you can simply do sum there (see below):

$db->query("SELECT SUM(costs) FROM table_name WHERE `date`='2016-01-02'");
echo $db->fetchColumn();

Upvotes: 1

Kausha Mehta
Kausha Mehta

Reputation: 2928

Try below code:

<?php 
$total = 0;
foreach((array)$query as $row):
    $date = $row->date;
    $cost = $row->cost;
    if(date("M-d-Y", strtotime($date))==date("M-d-Y")) {
        $total = $total+$cost;
    }
    ?>
    <td><?php echo $date ?></td>
    <td><?php echo $cost ?></td>
<?php endforeach; ?>

<td colspan="2"><?php echo $total; ?></td>

Upvotes: 0

fusion3k
fusion3k

Reputation: 11689

<?php
$tot = 0;
foreach( (array)$query as $row ) {
    if( $row->date=='02-01-2016' ) $tot = $tot+$row->cost;
?>
<tr>
<td><?php echo $row->date ?></td>
<td><?php echo $row->cost ?></td>
</tr>
<?php } ?>
<tr><td colspan="2"><?php echo $tot; ?></td></tr>

obviously, the comparison works if $row->date is formatted as dd-mm-yyyy

Upvotes: 0

Related Questions