-1

I was just working on some curl work, until I bumped into a interesting if statement. Thinking that it would never execute the if statement, to my surprise it does. How does this execute?

   <?php      
     while (6 && 2 == 2) {

     $test = "How the hell?!!?";

}
 ?>

The only reason I can think that it works is that 6 evaluates to true and 2 equals to 2 which is true. Am I correct in this thinking? Originally I thought it could not execute as 6 clearly dosen't equal 2.

Matthew Underwood
  • 1,459
  • 3
  • 19
  • 33
  • possible duplicate of [Reference - What does this symbol mean in PHP?](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Kermit Apr 25 '13 at 17:54
  • 2
    http://php.net/manual/en/language.operators.precedence.php `==` has a higher precedence than `&&`, so this is effectively `while (6 && true)`, which is always true. – Michael Berkowski Apr 25 '13 at 17:54
  • Have you looked at [operator precedence](http://php.net/manual/en/language.operators.precedence.php)? (Yes, your guess is right: `6 && 2 == 2` == `6 && (2 == 2)` == `6 && true` == `truthy && true` == `true`. – Wrikken Apr 25 '13 at 17:56
  • Voted up to offset some of the haters. I mean, you actually asked a programming question, but apparently it's not good enough for some people :) – vtacreative Apr 25 '13 at 18:09

3 Answers3

2

You are correct. For the order in which the sub-statements (6, &&, 2, ==, 2) are executed, see http://php.net/manual/en/language.operators.precedence.php.

So it's evaluated as (6) && ((2) == (2)). 6, casted to boolean is true. And 2 == 2 too. What results in true && true what's naturally true.

bwoebi
  • 23,637
  • 5
  • 58
  • 79
  • Thank you, sorry I forgot to check for same questions, I just wanted a direct answer to my example. Thanks agian. Will mark this as correct as soon as I get back from the shops and buy a birthday card. – Matthew Underwood Apr 25 '13 at 18:03
1

Correct. Your expression has two parts 6 and 2==2. Both are true so true && true is of course true. Look at operator precedence.

Håkan
  • 186
  • 6
1

I don't have any experience in PHP, but I'll take the shot. When doing logic comparisons, there will be a returned value, depending on the values on each sides. In C++ for example, you have two possible outcomes of a comparison: 0 and 1. 0 will stand for 'false', while 1 and any other number stands for 'true'. Therefore, in your code, you get a value that is 6 (which is not 0, so true), and a value that is 1 (because 2 equals 2).