Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int variable with leading zero?

Tags:

php

int

octal

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

intval(042);
like image 432
RoboTamer Avatar asked Jun 15 '11 04:06

RoboTamer


2 Answers

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
like image 120
AndreKR Avatar answered Sep 17 '22 17:09

AndreKR


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

like image 43
jcomeau_ictx Avatar answered Sep 18 '22 17:09

jcomeau_ictx