5

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

I'm following the PHP documentation on page Comparison Operators. 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?

2
  • Incidentally this is why it's usually best to use === instead of ==, since the result is far more predictable! Commented Jul 15, 2012 at 5:07
  • Re "compare strings using '==' is not the way": What is the way? Using three (===)? What is the canonical Stack Overflow question for it? Commented Jan 3, 2023 at 4:18

2 Answers 2

4

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)
?> 
Sign up to request clarification or add additional context in comments.

1 Comment

To expand on this, here is the explanation in the docs. php.net/manual/en/… "If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float."
0

Type Juggling is not equal to Type Casting

From the Type Juggling page

If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.