2

Just curious how PHP type casting work for this case.

var_dump(1 == '1,2') // boolean(true)
user2864740
  • 60,010
  • 15
  • 145
  • 220
xwlee
  • 1,083
  • 1
  • 11
  • 29

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
  • 68,075
  • 43
  • 96
  • 126
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
  • 43,890
  • 13
  • 88
  • 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,194
  • 4
  • 27
  • 43