Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour with numbers that have a leading zero [duplicate]

I have some PHP code with some integers and all works fine, except when I have 08 or 0X as integer. It all works fine when I put them in quote.

Example numbers:

2      //Works fine
08     //Doesn't work
012    //Doesn't work
"08"   //Works fine again
"012"  //Works fine again

Can anyone tell me the reason behind it?

like image 874
Manu Mathew Avatar asked Dec 12 '22 17:12

Manu Mathew


1 Answers

If you simply write 08 and 09 (without quotes) or any other numeric with a leading 0, PHP believes you're writing an octal value, and 08 and 09 are invalid octal numbers.

http://www.php.net/manual/en/language.types.integer.php

Syntax

Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +).

Binary integer literals are available since PHP 5.4.0.

To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b.

[...]

Warning: Prior to PHP 7, if an invalid digit was given in an octal integer (i.e. 8 or 9), the rest of the number was ignored. Since PHP 7, a parse error is emitted.

like image 185
Mark Baker Avatar answered Feb 12 '23 08:02

Mark Baker