6

Let's suppose I have a code which outputs $i as

$i = 016;
echo $i / 2;
//ans will be 7

I know that the leading zero indicates an octal number in PHP, but how is it interpreted, how can it be executed? Can somebody share its execution step by step? What is the role of parser here? I have researched a lot and read all the previous answers but none are having any deep explanation.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Jaymin
  • 1,643
  • 1
  • 18
  • 39
  • 2
    have a look at http://php.net/manual/en/language.types.integer.php – Chetan Ameta Aug 17 '17 at 05:56
  • 2
    The interpreter does the conversion during the compilation phase. The first line of code produces the same opcodes as `$i = 14;`. – axiac Aug 17 '17 at 05:56
  • What do you mean "deep explanation"? The parser sees an integer with a leading 0 and interprets it as octal number, thats's it!? :D – xander Aug 17 '17 at 05:58
  • Yes you can answer it in answer column by giving a proper explanation, will appreciate your efforts – Jaymin Aug 17 '17 at 05:59

2 Answers2

3

When you preceed integers with zero in PHP, in that instance, 029.

It becomes octal.

So when you echo that, it will convert to its decimal form.

Which results to:

echo 016; //14 (decimal) valid octal

echo 029; // 2 (decimal) -  Invalid octal

Actually, its here stated in the manual

Valid octal:

octal       : 0[0-7]+

Note: 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.

Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44
  • Yes your answer seems perfect to explanation only thing I will love to edit is 029 to 2 as it is not giving perfect decimal number instead use 016 to 14, so that anyone can interpret it easily. Thanks a ton :) – Jaymin Aug 17 '17 at 06:36
  • 1
    @JayminNoob: 029 is an invalid octal literal, so what is it supposed to do then? – Ignacio Vazquez-Abrams Aug 17 '17 at 06:37
  • @IgnacioVazquez-Abrams I have mentioned same thing, above what if it is invalid octal literal what it does next? – Jaymin Aug 17 '17 at 06:39
  • @JayminNoob i have addec 016 and also for invalid octal i added a note at the end of answer – Chetan Ameta Aug 17 '17 at 06:46
2

The octal numeral system, or oct for short, is the base-8 number system, and uses the digits 0 to 7.

Octal numerals can be made from binary numerals by grouping consecutive binary digits into groups of three (starting from the right).

For example, the binary representation for decimal 74 is 1001010. Two zeroes can be added at the left: (00)1 001 010, corresponding the octal digits 1 1 2, yielding the octal representation 112.

In your question $i = 016; is calculated by the interpreter and produces $i = 14;(which is the equilevant decimal number)

Then you simply divide it by 2, which outputs 7.

Sotiris Kiritsis
  • 3,178
  • 3
  • 23
  • 31