Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is Leading Zero working in php?

Tags:

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.

like image 277
Jaymin Avatar asked Aug 17 '17 05:08

Jaymin


2 Answers

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.

like image 81
Chetan Ameta Avatar answered Oct 11 '22 14:10

Chetan Ameta


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.

like image 23
Sotiris Kiritsis Avatar answered Oct 11 '22 14:10

Sotiris Kiritsis