How does Leading Zero work in php?

Suppose I have code that outputs $i as

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

I know that leading zero indicates an octal number in PHP, but how is it interpreted, how can it be executed? Can someone share their performance in stages? What is the role of the parser here? I have researched and read all the previous answers a lot, but no one has a deep explanation.

+5
source share
2 answers

When you chase integers with zero in PHP, in this case 029 .

It becomes octal.

So, when you echo, it will be converted to decimal.

What are the results:

 echo 016; //14 (decimal) valid octal echo 029; // 2 (decimal) - Invalid octal 

Actually, it is indicated here in manual

Valid octal:

 octal : 0[0-7]+ 

Note. . Prior to PHP 7, if an invalid digit was specified in octal integer (i.e. 8 or 9), the rest of the number was ignored. Starting with PHP 7, a parsing error occurs.

+2
source

The octal or short octal number system is a base-8 number system and uses digits from 0 to 7.

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

For example, the binary representation for decimal code 74 is 1001010. Two zeros can be added on the left: (00) 1 001 010, which corresponds to the octal digits 1 1 2, which gives an octal representation 112.

In your question $i = 016; computed by the interpreter and returns $i = 14; (which is the decimal number of equidistant)

Then you just divide it by 2, which yields 7.

+2
source

Source: https://habr.com/ru/post/1270950/


All Articles