开发者

PHP IF statement for Boolean values: $var === true vs $var

开发者 https://www.devze.com 2022-12-09 23:37 出处:网络
I know this question is not really important.. however I\'ve been wondering:开发者_如何学Python

I know this question is not really important.. however I've been wondering:开发者_如何学Python

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


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';
}


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.


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.


=== 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消