The if statement doesn't work for false in php

2020-07-10 07:13发布

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?

10条回答
一夜七次
2楼-- · 2020-07-10 07:28

As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section.

So as per docs try using

$con = false;//boolean and not a string
if($con){echo 'true';} else{echo 'false';} 

When converting to boolean, the following values are considered FALSE:

◦ the boolean FALSE itself
◦ the integer 0 (zero)
◦ the float 0.0 (zero)
◦ the empty string, and the string "0"
◦ an array with zero elements
◦ an object with zero member variables (PHP 4 only)
◦ the special type NULL (including unset variables)
◦ SimpleXML objects created from empty tags

Check Docs (IF MANUAL)

查看更多
倾城 Initia
3楼-- · 2020-07-10 07:30

'false' is not same as false.

if('true') or if('false') will result true always as they will be treated as strings and will be converted for comparison.

$con=false;
if($con){echo 'true';} else{echo 'false';} 

Will print false

查看更多
Viruses.
4楼-- · 2020-07-10 07:33

In your second example, $con isn't the boolean false, it's a string literal 'false' (note the quotes), and any non-empty string in PHP evaluates as true.

To fix this, just drop the quotes:

$con=false; // no quotes!
if($con){echo 'true';} else{echo 'false';} 
查看更多
做自己的国王
5楼-- · 2020-07-10 07:40

You are using 'false' as a STRING variable, but that is the WORD false, not the BOOLEAN constant. Just use false

if(true) {echo 'true';} else {echo 'false';}

$con='false';  // Wrong
$con=false; // Right
if($con){echo 'true';} else{echo 'false';} 

And when you are doing if statements, this will work:

if ($con == false) { echo 'false'; }

or you can use a === which compares one expression to another by value and by type.

if ($con === false) { echo 'false with type safe comparison!'; }
查看更多
登录 后发表回答