简体   繁体   中英

int variable with leading zero?

Why is it that following results in 34? It doesn't seem to have anything to do with octal numbers.

intval(042);

but a leading 0 does indicate octal in many languages, as is the case here.

It does have to do with octal numbers, 042 is interpreted as the octal number 42 which is 4 * 8 + 2 = 34 .

Please be aware that the octal interpretation happens when the number literal is parsed while loading the PHP script. It has nothing to do with intval() , which doesn't do anything here because the value is already integer.

Octal interpretation happens only with number literals, not when casting a string to integer:

intval(042)   // == 34
intval('042') // == 42
(int)'042'    // == 42

In PHP a number with leading 0 is read as an octal number.

So 042 is read as an octal number.

The intval() function converts it into decimal number, which is 34.

So the browser output is 34.

It's simply how the function is defined. The leading zero is an instruction parse it as an octal number, similarly as to how 0x as a prefix means hex. See the documentation for more information .

Be careful when passing this function a string value with a leading "0". If you give it "042" then, it will treat it as BASE 8 - 9 and convert it to decimal value, which is by default base.

Please go through this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM