0

I want to perform a specific action if all arrays in a multidimensional array meet a specific condition when two of their values are subtracted.

What loop could help me achieve this type of result as shown in my code below:

$array = Array( 
    [0] => Array("id" => 1, "value1" => 7, "value2" => 10), 
    [1] => Array("id" => 2, "value1" => 6, "value2" => 10), 
    [2] => Array("id" => 3, "value1" => 8, "value2" => 11), 
    [3] => Array("id" => 4, "value1" => 9, "value2" => 12),
    [n] => Array( ...)
);

$val1 = $array[0]['value2'] - $array[0]['value1']; // 10 - 7 = 3
$val2 = $array[1]['value2'] - $array[1]['value1']; // 10 - 6 = 4
$val3 = $array[2]['value2'] - $array[2]['value1']; // 11 - 8 = 3
$val4 = $array[3]['value2'] - $array[3]['value1']; // 12 - 9 = 3
$valn = $array[n]...

if ($val1 < 5 && $val2 < 5 && $val3 < 5 && $val4 < 5 ... && valn < 5){

  //from my example, the answer is TRUE for all
 // Do this action

}else{
 // Do something else

}
2
  • is your goal to process only those arrays which subtraction result is less than 5? Commented May 23, 2017 at 10:03
  • @RomanPerekhrest No., my goal is to process all arrays and return TRUE or FALSE if they are all less than 5 Commented May 23, 2017 at 10:06

1 Answer 1

1
$all_less_than_5 = true;
foreach($array as $item){
    if($item['value2'] - $item['value1'] >= 5){
         $all_less_than_5 = false;
         break;
    } 
}
if($all_less_than_5){
    // Do this action
}else{
    // Do something else
}
Sign up to request clarification or add additional context in comments.

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.