PHP Question: Octal Values

15th April 2011

Question

If I assign and print a value like this:

  1. $a = 012;
  2. print $a;

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









 

Answer

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:

  1. print base_convert($a, 10, 8);

Or even this:

  1. print decoct($a);

Or even this:

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

Comments

Permalink

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

Paweł (Fri, 04/15/2011 - 18:03)

Permalink

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

Pete (Wed, 04/27/2011 - 10:05)

Add new comment

The content of this field is kept private and will not be shown publicly.