PHP negatives keep adding

前端 未结 3 858
予麋鹿
予麋鹿 2021-01-29 16:48

I have this code here...

$remaining = 0;
foreach($clientArrayInvoice as $key=>$row){
            $remaining = $remaining + $row[\'total\'];   
}
相关标签:
3条回答
  • 2021-01-29 17:09

    This might help:

    (-51.75) + (-17.85) = -69.60
    (-51.75) - (-17.85) = -33.90
    

    Assuming you always need to add the second number regardless of it's sign, you need to take the absolute value by using the PHP abs function with $row['total']:

    $remaining = 0;
    foreach($clientArrayInvoice as $key=>$row){
        $remaining = $remaining + abs($row['total']);   
    }
    

    In response to what you updated in your question:

    -33.90 is the value I am expecting because when its two negatives I would like to subtract, not add

    This is pretty much what using the abs function does. I could rewrite the above code snippet as:

    $remaining = 0;
    foreach($clientArrayInvoice as $key=>$row) {
        if ($remaining >= 0) {
            $remaining = $remaining + abs($row['total']);   
        }
        else {
            $remaining = $remaining - abs($row['total']);   
        }
    }
    

    However, this does the exact same thing as simply using the PHP abs function, since you are always adding the magnitude of $row['total'] to $remaining.

    0 讨论(0)
  • 2021-01-29 17:24

    I am not sure what your question is exactly, but this would keep adding the absolute values if $remaining is negative until it is positive again.

    $remaining = $remaining + ($remaining < 0 && $row['remainingbalance'] < 0 ? -1 : 1) * $row['remainingbalance']);

    This works for your example, it would be 0 - 51.75 + 17.85 = -33.9. But I am not sure if it's the behavior you want in the bigger picture.

    0 讨论(0)
  • 2021-01-29 17:25

    again --> see php's abs() function if you want to add things and ignore the sign.

    0 讨论(0)
提交回复
热议问题