Is there a rule or guideline for when to use != instead of (!condition) when checking if a condition is true or false?
For instance, I have some pages that check if TLS is enabled before returning anything:
if ($_SERVER['HTTPS'] !== 'on') { exit; }
But I could also write it like this:
if (!$_SERVER['HTTPS'] === 'on') { exit; }
For some statements it seems cleanest to use the latter, for instance:
if (!isset($_SESSION)) { session_start(); }
… is shorter than the equivalent:
if (isset($_SESSION) == false) { session_start(); }
Is there a standard or guideline for writing these statements, or is it just preference?
Note: I understand the difference between == and ===, I just want to make sure my code is as clear and concise as possible.
Don’t do this:
! has higher precedence than ===, so this evaluates to:
In this case, !$x will cast $x to boolean, then invert it. So, if $x has anything at all in it, you’ll end up with:
And this will never match for any value of $x.