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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With