user3021621
user3021621

Reputation: 341

comparing type string numeric

in php.net the following is written:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value

  1. var_dump("10" == "1e1"); // 10 == 10 -> true
  2. var_dump(100 == "1e2"); // 100 == 100 -> true

why in the first example it is evaluated as true but, the statement $num = (int)"1e1" ; is evaluated as 1 and not 10??? furthermore, why in the second example it is evaluated as true but the statement $num = (int)"1e2" ; is evaluated as 1 and not 100??

Upvotes: 0

Views: 193

Answers (3)

Boolean_Type
Boolean_Type

Reputation: 3

1e1 is double.

var_dump("10" == "1e1");
// 10 (converts to real type, not int) == 10 (converts to real type, not int) -> true

My attempt to convert the numeric string (float type) to integer:

(int)'1E1'

It turns 1 instead of 100.

Upvotes: 0

Krzysztek
Krzysztek

Reputation: 9

  1. String and string comparison: "10" is the same string representation as "1e1".
  2. Int and string comparison: 100 as string is "100" or "1e2" and is the same representation as "1e2";
  3. Casting string to int: (int) "1e1" => 1 as intval("1e1").

Casting is not the same as equality.

Upvotes: 0

Anonymous
Anonymous

Reputation: 12017

I am not sure why (int)'1E1' displays 1 (it probably ignores all letters and anything after), but what works perfectly for me is this:

echo '1E1'*1; //returns 10

Upvotes: 1

Related Questions