Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string comparison using '=='

Tags:

php

comparison

I did a few tests with strings using '=='. I know to compare string '==' is not the way, but there is a weird behavior I want to solve.

I'm following the PHP documentation in this page: http://www.php.net/manual/en/language.operators.comparison.php . This is the test I did

<?php 
   var_dump( "100" == "1e2" ); //outputs boolean true
   var_dump( (int) "100" ); //int 100
   var_dump( (int) "1e2" ); //int 1
?> 

The documentation says when we compare strings with numbers, PHP first converts the string to numbers, but when I convert '100' and '1e2' to numbers they are not equal. The comparison should outputs boolean false.

Why is this weird behavior? Thanks!

like image 955
Jose Daniel Avatar asked Jul 15 '12 04:07

Jose Daniel


1 Answers

Not all numbers are integers. 1e2 is a float (that happens to be representable as an integer, but is not directly convertible to an integer). Try converting to floats rather than ints:

<?php 
   var_dump( "100" == "1e2" ); // bool(true)
   var_dump( (float) "100" );  // float(100)
   var_dump( (float) "1e2" );  // float(100)
?> 
like image 68
icktoofay Avatar answered Nov 14 '22 23:11

icktoofay