Sunday 18 March 2007

PHP: comparison of integer with string

PHP does not have explicit declarations of variable types. Whatever you put in a variable or array defines what the variable's type is. String, integer, boolean, float etc.

I have two variables, both containing a value. However somehow one of the variables is seen as a string, so when doing a comparison between the two strings it did not give a result. The variable was not explicitely loaded as a string, a value from the url is put in there using the GET method.

$var1=33 (integer)
$var2="33" (string)

if($var1 == $var2) {echo 'equal';}

This does not give a match. A quick although not very neat resolution is to make sure that var2 is seen as an integer. This can be done by using an arithmatic operator on the variable.

$var2++; //var2=34
$var2--; //var2=33

if($var1 == $var2) {echo 'equal';}

Results in the if-statement being true.

No comments: