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

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

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.

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}