Akki Akki -4 years ago 56
PHP Question

How to total sum of table using for loop in php

I created table using multi for loop and i get it result but i want result to total sum of table like :

My code are given below :

for($i=1; $i<=2; $i++)
{

for($j=1; $j<=3; $j++)
{
echo "<tr>";
$total = $i*$j;
$sum = $total+$j;
echo "<td>$i * $j = ".$total."</td>";
}
echo "</tr>" ;
echo "<br/>" ;
}


and My output is :

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6


But I Want result to total get multiply value like :

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3 1+2+3 = 6

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6 2+4+6 = 12


I Appreciate if anyone know this answer.

Answer Source

You need to sum the total for each loop.

for($i=1; $i<=2; $i++)
{   
$sum =0; // initiate sum variable with 0
    for($j=1; $j<=3; $j++)
    {
        $total = $i*$j;
        $sum += $total; // add total value to sum
        echo "$i * $j = ".$total."\n";  
    }

    echo "Sum = $sum\n" ; // echo sum value
}

Out Put:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
Sum = 6
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
Sum = 12
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download