2

Just curious how PHP type casting work for this case.

var_dump(1 == '1,2') // boolean(true)
user2864740
  • 57,407
  • 13
  • 129
  • 202
xwlee
  • 1,053
  • 1
  • 10
  • 27

3 Answers3

7

That is because 1 is an integer here and when it is compared to a string 1,2 , this string will be casted to an integer , which returns 1.

How does casting a string 1,2 return 1 ?

echo int('1,2'); // prints 1 

So when it is compared to your 1 , this will be obviously returning true on your var_dump

From the PHP Docs.. (Basic Comparison Test)

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

Source

Shankar Narayana Damodaran
  • 66,874
  • 43
  • 94
  • 124
4
  1. It's interpreted as:

    var_dump(1 === (int) '1,2');
    
  2. "1,2" casted to int will return 1, as anything after last parsed digit is being cutted off (,2 in this case).

  3. Remember that comma (,) is not a decimal point separator, dot (.) is:

    var_dump((float) '1,3', (float) '1.3');
    

    Results in:

    (float) 1
    (float) 1.3
    

Casting can be often very unintuitive, that's why you should almost always use === operator, which doesn't create casts.

Crozin
  • 42,946
  • 13
  • 87
  • 135
4

If you use ==, php will type cast the right side value to the left side value. In this case '1,2' will be type cast to 1 and return true.

Even var_dump( 1== "1dfuiekjdfdsfdsfdsfdsfsdfasfsadf" ); will return true.

Nauphal
  • 6,118
  • 4
  • 26
  • 43