How can i tell if a boolean is true in php?

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?


I know === is to match exactly the boolean value. However is there really any improvement?

asked Nov 3, 2009 at 21:07

MarioRicaldeMarioRicalde

8,7636 gold badges39 silver badges41 bronze badges

2

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.

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.

Chủ Đề