I have this code here...
$remaining = 0;
foreach($clientArrayInvoice as $key=>$row){
$remaining = $remaining + $row[\'total\'];
}
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
.
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.
again --> see php's abs() function if you want to add things and ignore the sign.