I have this array.
$val = array(1, 0, 2, 1, 1);
I want to subtract 3.5 from $val array in the way that from every element that element not become negative like this:
$val = array(0, 0, 0, 0.5, 1)
Iterate array items and in loop check if target value is great that loop item, subtract item value from target value. If loop item is great than target value, subtract target value from loop item.
$val = array(1, 0, 2, 1, 1);
$subtract = 3.5;
foreach ($val as $key => $item){
if ($subtract >= $item){
$subtract -= $item;
$val[$key] = 0;
} else {
$val[$key] -= $subtract;
$subtract = 0;
}
}
See result in demo
One other possible approach: reduce the subtract value by the value of the current iteration, then set the current value to either zero or -$subtract. Break when $subtract drops below zero.
foreach ($val as &$number) {
$subtract -= $number;
$number = ($subtract > 0) ? 0 : -$subtract;
if ($subtract <= 0) break;
}