8

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

Boann
  • 47,128
  • 13
  • 114
  • 141
Sugumar Venkatesan
  • 3,782
  • 7
  • 39
  • 71

3 Answers3

9

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.

Timurib
  • 2,693
  • 14
  • 26
Bhumi Shah
  • 8,909
  • 7
  • 57
  • 96
4

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

DonCallisto
  • 28,203
  • 8
  • 66
  • 94
1

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!';
Tobia
  • 8,843
  • 26
  • 98
  • 202