Home » Php » PHP why is 0=='all' true?

PHP why is 0=='all' true?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am reading the PHP documentation for boolean.

One of the comments says 0==’all’ is true.

http://php.net/manual/en/language.types.boolean.php#86809

I want to know how it becomes true.

The documentation says all non-empty strings are true except ‘0’.

So ‘all’ is true
and
0 is false.

false == true should be false.

But:

if(0=='all'){
    echo 'hello';
}else{
   echo 'how are you ';
}

prints ‘hello’.

How to&Answers:

In PHP, operators == and != do not compare the type. Therefore PHP automatically converts ‘all’ to an integer which is 0.

echo intval('all');

You can use === operator to check type:

if(0 === 'all'){
    echo 'hello';
}else{
   echo 'how are you ';
}

See the Loose comparisons table.

Answer:

As you have as left operand an integer, php tries to cast the second one to integer. So as integer representation of a string is zero, then you have a true back.
If you switch operators you obtain the same result.

As Bhumi says, if you need this kind of comparison, use ===.

Answer:

If you put a string as condition in a IF steatment it is checked to be not empty or ‘0’, but if you compare it with an integer (==, <, >, …) it is converted to 0 int value.

if('all')
    echo 'this happens!';
if('all'>0 || 'all'<0)
    echo 'this never happens!';