Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison Operators

Reffer this link.

I know operand with string type translate to number, and then usual math

But see these sample codes:

echo intval(1e1);       // 10
var_dump("1e1" == 10);  // true, and it's ok

echo intval(0x1A);      // 26
var_dump("0x1A" == 26); // true, and it's ok

echo intval(042);       // 34
var_dump("042" == 34);  // fasle, Why ?!!!

Why last code return false.

like image 820
Nabi K.A.Z. Avatar asked May 19 '26 20:05

Nabi K.A.Z.


2 Answers

That's because string-to-number conversion in PHP is based on some ancient C function - strtod. And its rules are as follows:

The expected form of the (initial portion of the) string is optional leading white space as recognized by isspace(3), an optional plus ('+') or minus sign ('-') and then either (i) a decimal number, or (ii) a hexadecimal number [...]

A decimal number consists of a nonempty sequence of decimal digits possibly containing a radix character (decimal point, locale-dependent, usually '.'), optionally followed by a decimal exponent. A decimal exponent consists of an 'E' or 'e', followed by an optional plus or minus sign, followed by a nonempty sequence of decimal digits, and indicates multiplication by a power of 10. [... ]

A hexadecimal number consists of a "0x" or "0X" followed by a nonempty sequence of hexadecimal digits possibly containing a radix character, optionally followed by a binary exponent. [...]

As you see, '1e1' string has non-empty sequence '1' followed by a decimal exponent 'e1'. So, it will be converted into a decimal number - and becomes 10.

'0x1A' string follows the rules for hexadecimal number, and will be converted into 26 accordingly. But as there's no specific rule for octadecimal number, '042' will be converted into a plain decimal - and becomes 42. Which is, of course, not equal to 34.

This should not be confused with how number literals are parsed by PHP itself. A number literal that starts with 0 is considered representing an octadecimal. So, intval(042) is essentially the same as intval(34) - but not the same as intval("042").

like image 54
raina77ow Avatar answered May 21 '26 11:05

raina77ow


That's how PHP rolls. It is because when you specify a string and convert, it gets converted to a number, In your case, the first 1e1 means 1 exponent 1, the 0x1A is hexadecimal representation and final part 042 itself is a number and it is converted to 42 but intval(042) means octal representation of integer 34.

like image 33
Deepak Avatar answered May 21 '26 11:05

Deepak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!