I have a dynamical fields that contains values and i need to do math with them. What is the way to do it in foreach
, do i have to save each value at the end of each loop?
Example there is 4 fields:
- $Field1 = 2; - $Field2 = 2; - $Field3 = 2; - $Field4 = 2; Example math formula: $sum = $Field1 * $Field2 + $Field3 - $Field4 ;
What i have is that I print these dynamical values into table and the table adapts users inputs:
<tbody> <?php foreach ($_POST['fields'] as $key => $value) : ?> <tr> <td><?php echo $value['description']; ?></td> <td><?php echo $value['hour_rate']; ?></td> <td><?php echo $value['hours']; ?></td> <td><?php echo $value['fixed_cost']; ?></td> <td><?php echo $value['discount']; ?></td> <td?<?php echo $SUM ?> </td> </tr> <?php endforeach; ?> <tr></tr> </tbody>
I can get TOTAL SUM (in this case $SUM in table) of all these values, but not 1 by 1.
$kopa+= number_format($value['hours'], 2)* number_format($value['hour_rate'], 2) + number_format($value['fixed_cost'], 2) - number_format($value['discount'], 2);
How can i get total value of each loop?
Thanks in advance.
Advertisement
Answer
Create a function with your formular and a extra foreach. Use the function inside your foreach loop. You can even loop over the fields in the array. (If you get them as array.)
function doMath ($array){ $sum = $array['field1'] * $array['field2'] + $.. return $sum; } foreach ($whatever as $key => $value) { echo doMath ($array ['withFields']); }