0

If I have following value, $result = 0, $request = 50 and $array = [25, 20], How do I reset and subtract $request value to $array values if $request value is greater than $array. and foreach will break if condition are $request less than $array value or, $request = 0 or, $array values = 0.

So condition like this and $result will be 5.

50      -    [25, 20]
|___   >=   __|    |
   25      00      |
   |_  >=  ________|
     5    00

code:

while(true) {
    $reset    = false
    $result   = 0;
    foreach($array as $key => $value) {
        if($request >= $value) {
            ....
        } else {
            ....
            $reset = true;
            break;
        }
    }

    if(!$reset) {
        break;
    }
}
2
  • What are thou using $result for? Commented Jun 10, 2016 at 6:43
  • $result was the subtracted value of $request and $arrays. Commented Jun 10, 2016 at 6:51

2 Answers 2

1

$request will be same as $result, so it's the same thing and therefore not needed.

$request = 50;
$array = array(25, 20);

foreach($array as $key => $value) {
    if($request < $value || $request === 0 ) {
      break;
    }

    $request = $request - $value;
}

echo 'Result: '.$request;

TESTS

$request = 50;

$array = array(25, 20); 
// Result: 5

$array = array(25, 30); 
// Result: 25

$array = array(25, 25); 
// Result: 0

$array = array(51, 10);
// Result: 50

EDIT

Edit based on comments and OP fiddle.

$request = 50;
$array   = array(20, 25, 25);
$excess = max(array_sum($array) - $request, 0);

foreach($array as $key => $value) {
    if($request < $value || $request === 0 ) {
      $request = 0;
      break;
    }

    $request = $request - $value;
}


echo 'Result: '.$request.'<br />';
echo 'excessValue: '.$excess;

TESTS

$request = 50;

$array  = array(25, 20);
// Result: 5, excess: 0

$array = array(50, 20);
// Result: 0, excess: 20

$array   = array(52, 5);
// Result: 0, excess: 7

$array   = array(20, 25, 25);
// Result: 0, excess: 20
Sign up to request clarification or add additional context in comments.

5 Comments

Is it possible whenever there's an array value loop will continue i.e $array = (10, 20, 30) or $array = array (28, 25, 10) ? until $request value becomes 0 or $request < $value.
Isn't it what it does right now? I'm not following. Whats desired result for $array = array (28, 25, 10)?
yes sir. there's a possibility I have several array values.
Can you give me examples and desired output?
Edited my answer and not have desired output and $excess variable too.
0
<?php 
while(true) {
    $reset    = false;
    $result   = 0;
$request = 51;
$array = array(25, 20); 

foreach($array as  $value) {
    if($request>=$value){
        $request=$request-$value;
    }
    else{
    break;
            }
echo 'Result: '.$request;
    }
    if(!$reset) {
        break;
    }
}
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.