3

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)

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.