Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP why is 0=='all' true? [duplicate]

Tags:

php

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'.

like image 418
Sugumar Venkatesan Avatar asked Jun 14 '18 07:06

Sugumar Venkatesan


2 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.

like image 128
Bhumi Shah Avatar answered Nov 09 '22 14:11

Bhumi Shah


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 ===.

like image 4
DonCallisto Avatar answered Nov 09 '22 12:11

DonCallisto