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
  • 48,794
  • 16
  • 117
  • 146
Sugumar Venkatesan
  • 4,019
  • 8
  • 46
  • 77

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,735
  • 16
  • 29
Bhumi Shah
  • 9,323
  • 7
  • 63
  • 104
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
  • 29,419
  • 9
  • 72
  • 100
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
  • 9,165
  • 28
  • 114
  • 219