When trying to get familiar with if
statement in PHP, this happened.
First time i tried this code below.
if(true) {echo 'true';} else {echo 'false';}
And the output was true
when the condition is true
. Again, when the condition is false
(if(false)
) it echos false
.
But i tried the same, using a variable as the condition, while changing the value of the variable.
$con='false';
if($con){echo 'true';} else{echo 'false';}
At this situation the output is true
even when the variable value is false
or true
. At the same time, the if statement
working fine when 1
and 0
is used instead true
and false
. Why is this happening?
PHP does some sneaky things in the if expression. The following values are considered FALSE:
Every other value is considered TRUE (including any resource).
You're actually passing a string that says the word false, rather than the value false itself. Because that isn't in the above list, it is actually considered true!
change the value of your variable to this
You can assign value to variable like this
Use a bool instead of a string:
Your if statement will simply check that $con is not empty, so in your example it will always be true.
That
'false'
is a valid string which is not BooleanFALSE
, just like$con='hi';
isn't.To quote from the Manual
Also read these other options that you have
Then you observed this
This is because 0 in any form is FALSE, either string or numeric. But the text
false
as a string is not false for reasons mentioned above.Also read about PHP Strict Comparisons since you're learning, because
Your $con declaration is a string not a bool. So it will always return true. To declare a boolean, use: