Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the expression 011 == 11 evaluate to false? [duplicate]

Tags:

php

When I was practicing in php, I noticed, that the following expressions yield strange results:

011 == 11   // false
'011' == 11 // true

Shouldn't they both evaluate to same result?

like image 273
Beso Kakulia Avatar asked Jul 30 '16 11:07

Beso Kakulia


1 Answers

This is because 011 is treated as an octal value because of the leading 0.

Here's the more in-depth explanation:

  1. The 011 literal is recognized as an octal value
  2. It is then converted to decimal value, which equals to 9
  3. The actual comparison happens which looks like the following: 9 == 11 // false

As of the '011' == 11, it evaluates to true, because when string is compared to integer, it's coerced to the integer value as well. Interestingly, the leading zero in the string is ignored in the proccess and the php interpreter treats the value as a decimal rather than an octal one!

like image 173
Alex Lomia Avatar answered Nov 01 '22 15:11

Alex Lomia