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

拜拜、爱过 提交于 2019-12-17 16:27:20

问题


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?


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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.




回答5:


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


来源:https://stackoverflow.com/questions/1670138/php-if-statement-for-boolean-values-var-true-vs-var

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!