Friday, 10 August 2018

PHP Question: Octal Values

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);

0 comments:

Post a Comment