Question

Just curious how PHP type casting work for this case.

var_dump(1 == '1,2') // boolean(true)
Était-ce utile?

La solution

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

Autres conseils

  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.

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top