Search code examples
phpintegeridentityequalityscientific-notation

Why is scientific notation not identical to integer in php?


I just wondered why my if statement was not entered when using scientific notation, i.e. 1e2 instead of 100 and 1e6 instead of 1000000.

It turns out, those are only equal and not identical, as seen by the following code:

<?php
echo "Integer: " . 100; // prints 100
echo "\n";
echo "Scientific notation: " . 1e2; // prints 100
echo "\n";

echo "Equality: ";

if(100 == 1e2) {
    echo "as expected";
} else {
    echo "wtf php";
}
// prints "Equality: as expected"


echo "\n";
echo "Identity: ";

if(100 === 1e2) {
    echo "as expected";
} else {
    echo "wtf php";
}
// prints "Identity: wtf php"

I have run it on different php versions and it seems to at least be consistent, as this behavior is the same across: 4.3.0 - 5.0.5, 5.1.1 - 5.6.27, hhvm-3.10.0 - 3.13.2, 7.0.0 - 7.1.0RC5.

Yet: Why!?


Solution

  • === operator, in php, consider the type of the operands. 1e2 even return a float number, and 100 is an integer. so, it's equals in values (==), but not in types (===).