Weird PHP String Integer Comparison and Conversion

I was working on some data analysis code when 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 create false , but, to my surprise, the dump was true !

I understand that in PHP there is such a type conversion:

 $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 the one I mentioned in the first example convert my string to an integer instead of converting an integer to a string.

I understand that you can do string comparison === in my example, but I just want to know:

  • Is there any part of the PHP documentation that is mentioned in this behavior?
  • Can someone explain why is happening in PHP?
  • How can programmers prevent such a problem?
+6
source share
2 answers

If I return, PHP will add two variables to the smallest type possible. They call it type juggling.

try: var_dump("something" == 0); for example, it will give you the truth., once it bit me.

Additional information: http://php.net/manual/en/language.operators.comparison.php

+4
source

I know that this has already been answered and accepted, but I wanted to add something that can help others who find it through a search.

I had the same problem when I was comparing a column array and keys in a PHP array, where in my post array I had an extra string value.

 $_POST["bar"] = array("other"); $foo = array(array("name"=>"foobar")); foreach($foo as $key=>$data){ $foo[$key]["bar"]="0"; foreach($_POST["bar"] as $bar){ if($bar==$key){ $foo[$key]["bar"]="1"; } } } 

From this, you might think that at the end of $foo[0]["bar"] will be equal to "0" , but it happened that when $key = int 0 was freely compared with $bar = string "other" , the result was true , to fix this, I am strictly comparing, but then it is necessary to convert the value of $key = int 0 to $key = string "0" when the POST array was defined as array("other","0"); . It worked:

 $_POST["bar"] = array("other"); $foo = array(array("name"=>"foobar")); foreach($foo as $key=>$data){ $foo[$key]["bar"]="0"; foreach($_POST["bar"] as $bar){ if($bar==="$key"){ $foo[$key]["bar"]="1"; } } } 

The result was $foo[0]["bar"]="1" if "0" was in the array of POST columns and $foo[0]["bar"]="0" if "0" not in the array POST columns.

Remember that when comparing variables, variables cannot be compared, because, in your opinion, due to incorrect PHP variable settings.

+1
source

Source: https://habr.com/ru/post/908321/


All Articles