How do you check if a boolean is true in php?
I know this question is not really important.. however I've been wondering: Show Which of the following IF statements is the best and fastest to use?
I know === is to match exactly the boolean value. However is there really any improvement? asked Nov 3, 2009 at 21:07
MarioRicaldeMarioRicalde 8,7936 gold badges39 silver badges41 bronze badges 2 Using
answered Nov 3, 2009 at 21:09
0 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.
Just a fact:
The second one is faster than the first.
gmadd 1,1469 silver badges17 bronze badges answered Feb 1, 2010 at 18:48
I'm not really deep into the technical stuff of PHP, but in the first case
$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
$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. answered Nov 3, 2009 at 21:14
Niels BomNiels Bom 8,2328 gold badges44 silver badges57 bronze badges === 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.
answered Nov 3, 2009 at 21:12
easementeasement 6,0713 gold badges28 silver badges35 bronze badges 1
How do you know if a boolean value is true?To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean. Copied!
What evaluates to true in PHP?Summary. A boolean value represents a truth value, which is either true or false . PHP evaluates the following values to false: false, 0, 0.0, empty string (“”), “0”, NULL, an empty array; other values are true .
Is 1 true or false in PHP?The boolean values are called true and false in php. In the case of true , the output is 1 . While with the false , it does not show any output.
Is bool true 1 or 0?The boolean type. The bool represents a value, which could only be either true or false . If you cast a bool into an integer, true will be 1 and false will be 0.
|