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?
The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.
Boolean Variables and Data Type ( or lack thereof in C ) C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.
Value 0 and 1 is equal to false and true in php.
The if statement will evaluate whatever code you put in it that returns a boolean value, and if the evaluation returns true, you enter the first block. Else (if the value is not true, it will be false, because a boolean can either be true or false) it will enter the - yep, you guessed it - the else {} block.
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'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With