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

点点圈 提交于 2019-11-27 22:45:21

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.

dan_nl

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

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