0

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??

1

3 Answers 3

1

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

2 Comments

if you will run the script you will see that the output is like what I'm saying, and I've tried 1E1 and still turns to 1. my question is why when comparing numerical strings then the it 1E1 is converted to 10 and when I try to convert it by casting to int it is converted to 1????
I updated the answer and I believe I understand what you are asking now.
0
  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.

Comments

0

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.

2 Comments

This is not really an answer to the question why it is happening
To understand why, you need to look at the source code. Otherwise - just accept as fact: it is a feature of parsing strings during conversion to integer (e - is a literal character, it is discarded).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.