PHP Question: Octal Values


If I assign and print a value like this:

$a = 012;
print $a;

I get back a value of '10', why?



This is because prefixing a number with a 0 in PHP forces the number to be interpreted as an octal value. However, it is stored internally as an integer value so when it is printed we get the integer value back. To get back the original octal value you could do something like this:

print base_convert($a, 10, 8);

Or even this:

print decoct($a);

Or even this:

print sprintf("%o", $a);


in this case if you add first zero, php will interpreted the variable as octal number and convert this value to decimal number (?) ;p


The title of the post gave this away, otherwise you might have got me with this one :)


Add new comment

The content of this field is kept private and will not be shown publicly.
6 + 10 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.