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?
So as per docs try using
Check Docs (IF MANUAL)
'false'
is not same asfalse
.if('true')
orif('false')
will resulttrue
always as they will be treated asstring
s and will be converted for comparison.Will print
false
In your second example,
$con
isn't the booleanfalse
, it's a string literal'false'
(note the quotes), and any non-empty string in PHP evaluates astrue
.To fix this, just drop the quotes:
You are using 'false' as a STRING variable, but that is the WORD false, not the BOOLEAN constant. Just use false
And when you are doing if statements, this will work:
or you can use a === which compares one expression to another by value and by type.