Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

PHP Data Types - Octal Notation

DZone's Guide to

PHP Data Types - Octal Notation

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Mike Bernat, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}