I know this question is not really important.. however I've been wondering:
Which of the following IF statements is the best and fastest to use?
<?php
$variable = true;
if($variable === true)
{
//Something
}
if($variable)
{
// Something
}
?>
I know === is to match exactly the boolean value. However is there really any improvement?
Using
if ($var === true)
orif ($var)
is not a question of style but a question of correctness. Becauseif ($var)
is the same asif ($var == true)
. And==
comparison doesn’t check the type. So1 == true
is true but1 === true
is false.I'm not really deep into the technical stuff of PHP, but in the first case
$variable has to have the exact same type as true for the if statement to be true. In other words, $variable has not only to resolve to true, but also has to be a boolean. So that's 2 operations, value-checking and type-checking.
In the second case
$variable only has to resolve to true. So only value checking occurs. I infer that that takes the computer a little less time.
Practically speaking: the differences in speed are probably negligible.
=== is really helpful in strstr/stristr when the first needle is in position 0 in the haystack. If you don't use === or !== you could have a bug on your hands.
Just a fact:
time php -r '$r = true; for($i = 0; $i < 10000000; $i++) { if($r == true) {} }'
time php -r '$r = true; for($i = 0; $i < 10000000; $i++) { if($r) {} }'
The second one is faster than the first.
As far as speed, I agree with Niels, it's probably negligible.
As far as which if statement is best to test with, the answer probably depends on the expected casting and values $variable can have.
If $variable is using 0 and 1 as a true/false flag then if ( $variable ) or if ( !$variable ) would work, but if it's an integer result as in strpos() you'll run into problems ... if possible, I'd recommend using an actual boolean value rather than 0 / 1.
... maybe this will help clarify; comment out the variations of $var to see the various results.