I was working on some data parsing code while I came across the following.
$line = "100 something is amazingly cool";
$key = 100;
var_dump($line == $key);
Well most of us would expect the dump to produce a false
, but to my surprise the dump was a true
!
I do understand that in PHP there is type conversion like that:
$x = 5 + "10 is a cool number"; // as documented on PHP manual
var_dump($x); // int(15) as documented.
But why does a comparison like how I mentioned in the first example converts my string to integer instead of converting the integer to string.
I do understand that you can do a ===
strict-comparison to my example, but I just want to know:
- Is there any part of the PHP documentation mentioning on this behaviour?
- Can anyone give an explanation why is happening in PHP?
- How can programmers prevent such problem?