Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 545
MarioRicalde Avatar asked Nov 03 '09 21:11

MarioRicalde


People also ask

How can check boolean value in if condition in PHP?

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.

Is bool true 1 or 0?

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.

Does 1 equate to true in PHP?

Value 0 and 1 is equal to false and true in php.

How check bool value in if condition?

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.


2 Answers

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.

like image 176
Gumbo Avatar answered Oct 02 '22 11:10

Gumbo


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'; } 
like image 37
2 revs Avatar answered Oct 02 '22 12:10

2 revs