PHP negatives keep adding

2020-05-11 10:10发布

问题:

I have this code here...

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

What it does, it takes the values of total and adds them up...but when I have values that are negatives, it adds them up as well for an example when I have -51.75 and -17.85 I get -69.60 which it should be -33.90 how do I fix this?

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

Thanks, J

回答1:

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.



回答2:

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



回答3:

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.