3

I have a very simple question. In PHP,

if ('abc' == 0){
    //true
}
if ('abc' == 1){
    //false
}

I know that this page tell us that it is supposed to be like that. But, I find it wierd. In addition,

if ('abc' == true){
    //true
}
if ('abc' == false){
    //false
}

What is the logic behind theses two conversions?

Gab
  • 5,604
  • 6
  • 36
  • 52
  • 1
    Explained here http://stackoverflow.com/questions/12151997/why-does-1234-1234-test-evaluate-to-true/12152223#12152223 – Mike B Feb 18 '14 at 21:04
  • I avoid this sort of messiness by using strict comparison (`===`) and typecasting things (`$foo = (int)$_POST["bar"];`). – miken32 Feb 18 '14 at 21:10

2 Answers2

4

Conversion 1

When string and integer comparisons are made, the string is converted to an integer first and then the comparison is made. Since there are no leading integers in those strings they convert to zero.

Conversion 2

Any non-empty string values are boolean true.

From the manual:

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

See also: Type Comparisons

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 1
    There's also http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting :-D – gen_Eric Feb 18 '14 at 21:05
1

The relevant table can be found here. It is important what type both operands have, based on that one or both values will be converted.

In your first case, the rules of both sides being "string, resource or number" is the first applicable, and the rule is "Translate strings and resources to numbers, usual math".

For the second example, the "Convert both sides to bool, FALSE < TRUE" rule fits.

deceze
  • 510,633
  • 85
  • 743
  • 889