0

I am trying to compare each element from two array $min and $max

$test = false;
$min = array(2,3,3,55,556);
$max = array(22,32,4,56,557);
foreach($min as $key=>$val){
    foreach($max as $k=>$v){
      if($val >= $v){
        $test=true;
        break;
      }
  }
}


if($test){
  echo "A NOT GREATER THAN or EQUAL B";
}else{
  echo "YOU CAN SAVE NOW";
}

What I am wrong?because I got the message here

  A NOT GREATER THAN or EQUAL B

thanks

2
  • I'm guessing what you're trying to do is see if every element in the first array, is >= it's equivalent element in the second array? Is this true? Commented Feb 18, 2011 at 10:41
  • yes,it's equivalent element in the second array Commented Feb 18, 2011 at 10:44

4 Answers 4

4

You're comparing every value from $min with every value from $max (until you hit a value of $min that is greater than a value in $max), and 55 from $min is greater than 22 from $max, so $test will be set to true.

Are you simply trying to compare corresponding $min and $max values?

$test = false;
$min = array(2,3,3,55,556);
$max = array(22,32,4,56,557);
foreach($min as $key=>$val){
   if($val >= $max[$key]){
     $test=true;
     break;
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Lol, literally exact same code/comment like 2 mins apart. Well played :-P
1

Well, 55 and 556 from the $min array are greater than 22,23,4,56 from the $max array. Are you trying to just compare the matching items?

If so then your code should look like this:

foreach($min as $key=>$val){
   if($val >= $max[$key]){
       $test=true;
       break;
   }       
}

1 Comment

It is the same code @Mark.,both the same idea ,thanks @Alexandru.
0

You have to use "break 2" to break both foreach. With "break" (or "break 1") you only stop the nested foreach. But Mark is right, the loop itself is wrong.

Comments

0

No, this is of the condition u have given there, the loop is stopping when the 556 compare starts with 22, immediately the loop is break and so u r getting that message.

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.