1

I was just wandering the about the concept of equating the condition in PHP that is,

what could be the difference between

true == isset($variable) 

and

isset($variable) == true

?

OM The Eternity
  • 15,694
  • 44
  • 120
  • 182

5 Answers5

3

For this specific case, no difference.

The first syntax is used to prevent accidental assignment instead of comparison.

if ( true = $x ) // would yiled error
if ( $x = true ) // would work

But again, in your case, no difference.

Elaboration:

Say you want to compare a variable $x to true and do something. You could accidentally write

if ( $x = true )

instead of

if ( $x == true )

and the condition would always pass.

But if you get into the habit of writing

if ( true == $x )

these mistakes wouldn't happen, since a syntax error would be generated and you would know in advance.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Can u please elaborate @Luchian – OM The Eternity Jan 27 '12 at 09:08
  • But Here I am comparing it, not assigning – OM The Eternity Jan 27 '12 at 09:09
  • 1
    The idea is to prevent *accidental* assignment. See 'Yoda conditions' here: http://stackoverflow.com/questions/3757941/yoda-conditions-and-integer-promotion – g t Jan 27 '12 at 09:10
  • Great Clarification I Have Upvoted it, I Have not Downvoted it..THanks – OM The Eternity Jan 27 '12 at 09:15
  • 1
    hmmm, never really thought of doing that to prevent accidental assignment. I always just think it looks odd, less readable code if your just quickly scanning through a document. +1 for the explanation though as I see this in other people's code quite a bit and never understood why they'd do it the wrong way round (in a logical sense). – Nick Jan 27 '12 at 09:18
3

There is no difference. But isset() itself returns a boolean value.

So never use

if (true == isset($variable))

Just:

if (isset($variable))
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Remember that when php parses that true is actually defined and its equal to 1. Furthermore so is false and it is equal to 0. php automatically checks these for comparison with these values in an IF statement. You'll be safe using the ! operator, because its the same as if ($something == false) good luck!

Adam Fowler
  • 1,750
  • 1
  • 17
  • 18
-1

There is no "real" diffrences(in this case)
Between
true == isset($variable)
AND

 isset($variable) == true
Oyeme
  • 11,088
  • 4
  • 42
  • 65
-1

Would it be Java, there was difference.

i.e.

  String test = null;
  if("".equals(test)){
    System.out.println("I m fine..");
  }
  if(test.equals("")){
    System.out.println("I m not fine..");
  }
Waqas Memon
  • 1,247
  • 9
  • 22