Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird PHP String Integer Comparison and Conversion

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?
like image 294
mauris Avatar asked Feb 13 '12 08:02

mauris


1 Answers

If I recal correcly PHP 'casts' the two variables to lowest possible type. They call it type juggling.

try: var_dump("something" == 0); for example, that'll give you true . . had that bite me once before.

More info: http://php.net/manual/en/language.operators.comparison.php

like image 126
the JinX Avatar answered Oct 30 '22 23:10

the JinX