phpbcmath

How to add many values in a good way with bcmath?


If I want to add several values together with BCMath I could do like this:

$total_cost1 = bcadd($value1, $value2);
$total_cost2 = bcadd($value3, $value4);
$total_cost3 = bcadd($value5, $value6);
$total_cost4 = bcadd($value7, $value8);

$total_cost = 
    bcadd(bcadd($total1_cost, $total2_cost), 
    bcadd($total3_cost, $total4_cost));

but it makes it so unreadable and it would be easy to make mistakes. Please tell me there is a another way of solving this...!?


Solution

  • There's nothing wrong with that approach, just hide it.

    You can write a generic function which takes an array of numbers and adds them in a loop.

    Then you can simply: bcsum(array($value1, $value2, ....))