views:

973

answers:

5

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?

+14  A: 

Using if ($var === true) or if ($var) is not a question of style but a question of correctness. Because if ($var) is the same as if ($var == true). And == comparison doesn’t check the type. So 1 == true is true but 1 === true is false.

Gumbo
+2  A: 

=== 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.

$str = "four score and...";
$position = strstr($str,'four');
if($position===FALSE) return FALSE;
easement
Small comment on your code: I would always use curly braces {} around a codeblock after an if statement. I know it's not necessary, but imho it's good for readability.
Niels Bom
+1  A: 

I'm not really deep into the technical stuff of PHP, but in the first case

if($variable === true)

$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

if($variable)

$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.

Niels Bom
+1  A: 

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.

<?php

$var = true;
$var = 1;

$var = false;
$var = 0;

if ( $var ) {
    echo 'var = true <br />';
}

if ( $var === true ) {
    echo 'var is a boolean and = true';
}

if ( !$var ) {
    echo 'var = false <br />';
}

if ( $var === false ) {
    echo 'var is a boolean and = false';
}
dan_nl
A: 

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 is faster than first.

Anton Maryanov