PHP negatives keep adding

前端 未结 3 859
予麋鹿
予麋鹿 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.

提交回复
热议问题