# Comparison between a numeric and an alphanumeric string

13

The following operation returns true:

``````var_dump("1" == "1e0"); //1 == 1 -> true
``````

But if I add an "e" at the end of the second string, it returns false:

``````var_dump("1" == "1e0e"); //1 == 1 -> false???
``````

If you do the following, return 2:

``````echo (int)"1" + (int)"1e0e"; // 2
``````

My question is because the second operation returns false if in the third operation, I am converting the values to integer and returns 1 + 1, ie in the second operation the comparison should be 1 == 1, would not have to return true?

Another question is if I am comparing 2 strings, why does the first operation return true if there are two different strings?

asked by anonymous 26.08.2014 / 19:58

15

1e0 is the scientific notation for 1 `i.e 1 vezes 10 elevado a 0.` E php converts numeric strings in numbers to make the comparison.

``````var_dump("1000" == "1e3"); //1000 == 1000 -> true
var_dump("1" == "1e0"); //1 == 1 -> true
``````

1e0e is not a

``````var_dump("1" == "1e0e"); //1 != da string "1e0e"
``````

Whenever you do the casting you will see that this occurs because casting forces the conversion to integer:

``````var_dump((int)"1" == (int)"1e0e"); // true
``````

26.08.2014 / 20:05
8

To avoid confusion at the time of the comparison use `===` instead of `==` , so in addition to content PHP will compare type too.

``````var_dump("1" === "1e0"); // false
``````

String `"1"` is different from string `"1e0"`

``````var_dump("1" === "1e0e"); // false
``````

String `"1"` is different from string `"1e0e"`

``````var_dump((int)"1" == (int)"1e0e"); // true
``````

Integer `1` is equal to integer `1`

26.08.2014 / 20:19
3

Compare `===` does not resolve, see `0xFA` is 250, so (250 === 0xFA) results in `TRUE`

1) Compare the length of a string for an input that is: `0xFA`

``````if( \$string <= 255 ) // 250 < 255 // Logo retornará TRUE
``````

2) Convert to string causes the same effect:

``````( (string)255 === (string)0xFF )
``````

Here you have a simple string comparison, `1e0e` does not assume integer value and `1 == 1` is not the operation that occurs.

``````var_dump("1" == "1e0e"); //1 == 1 -> false???
``````

Here you have `1e0e` as a string and when it converts to INT, it naturally assumes the value of 1, which added to 1 results in 2;

``````echo (int)"1" + (int)"1e0e"; // 2
``````

If you want to compare effectively, you will need to do a combination of checks:
. You can force the input to assume a string value with `(string)\$input`
. Combine `mb_strlen` to compare the length of the entries.