2009.02.01

I just ran into an interesting question while studying for the Zend certification exam, and I thought I would share because I was very confused.

Q: What is the output of the following:

<?php
$a 
010;
$b 0xA;
$c 2;

print 
$a $b $c;
?>

Scroll down for the answer and explanation.

.

.

.

.

.

.

.

.

.

This questions deals with the many data-types that PHP accepts for variable assignments. I knew that the assignment for $c was hexadecimal and that a 'A' represented decimal 10. $c is obvious because it is in plain old decimal format as well. However, $a threw me for a loop. I thought that it would be interpreted as decimal 10, and that the leading 0 would just be tossed as being extraneous. Boy was I mistaken.

I got the answer wrong. I thought since $a = 10, $b = 10, and $c = 2, the answer was 22. However the answer provided by the test was 20. I was about to write an email to the mock-test group when I decided to take the 5 seconds and do some investigating.

I var_dumped each assignment and was startled to discover that $a = 8, not the 10 I originally thought.

<?php
var_dump
($a 010); // 8
var_dump($b 0xA); // 10
var_dump($c 2);   // 2

print $a $b $c; // 20
?>

Why was this? After some digging I found that in addition to the decimal and hexadecimal formats accepted by PHP, Octal was also accepted. I knew very little about octal values. The quick description is:

Octal notation - identified by its leading zero and used mainly to express UNIX-style access permissions.

Some examples:

<?php
var_dump
(0001); // 1
var_dump(0005); // 5
var_dump(0010); // 8
var_dump(0011); // 9
var_dump(0017); // 15
var_dump(0030); // 24
var_dump(0100); // 64
var_dump(0110); // 72
?>

I hope, like me, you learned something new today.

Get my RSS Feed!

Comments

Mat Wright on (2.23.2009 5:42 pm) says

Hi Mike,

Yes 010 could easily be mistaken for a decimal ten or even a binary two, when in fact its an oct eight.

You can use the following functions to do quick conversions between bin,oct,hex and dec:

bindec("111");//7
octdec("010");//8 :)
hexdec("0xa");//10

and viceversa (decbin, decoct,dechex)

base_convert() can be used to convert number of any base to another for example:

base_convert('010',8,10);//8

Mat Wright

 

David on (12.13.2009 12:31 am) says

nice ...thx

 
* Name
* Email (Will not be displayed)
Website