Jump to content

is there a difference between if($var == false) and if(false == $var)


jaikar

Recommended Posts

No there isn't. It's just comparing. It's the same as asking if this apple is the same color as this orange; or you might as well ask if this orange is the same color as this apple.

 

But there is difference in $var == false and $var === false

 

$var = 0;

$var == false // TRUE

$var === false // FALSE

 

=== will also compare the variable type. It checks if it's a bool, string or integer for example.

 

$var = "1";

 

$var == 1 // TRUE

$var === 1 // FALSE

Link to comment
Share on other sites

Which is the same as the logical operator ! (NOT)

 

$var = false;

if (!$var)
{
echo "var is equal to false";
} else {
echo "var is equal to true";

}

 

Returns var is equal to false.

 

It would be

 

if ($var != true)

 

if(!$var) and if($var != true) or if($var == false) all produce the same result -> "var is equal to false" (not entirely correct it could be aswell: null, '', array(), 0).

 

Junior programmers are often told to write if(false == $var) to make sure they'll never write if(false = $var) or if(1 = $var) as this will produce a fatal error, you can't redefine false nor 1.

 

In case of boolean variables (depending on your companies coding guidelines) you can shorten if($var == false) to if(!$var) as you actually say the same thing: execute when $var = false

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.