Have you ever seen this code and wondered why the answer isn’t what you expect?
$y = 012;
$x = $y / 2;
echo $x;
Most people would guess the output should be 6
. After all, 012
looks like a decimal number. But when you run the code, PHP prints 5! So, what's going on?
The answer lies in how PHP handles integers and number systems. Let’s unravel the mystery.
In PHP, integers are numbers that can be written in decimal, octal, hexadecimal, or binary. The way a number is represented depends on its prefix:
10
).0
(e.g., 012
).0x
(e.g., 0xA
).0b
(e.g., 0b1010
).So, what’s happening in our code?
$y = 012;
The leading 0
tells PHP to interpret 012
as an octal (base-8) number. In base-8:
Thus, 012
in octal is: 1⋅8^1+2⋅8^0=8+2=10 (in decimal)
When divided by 2:
$x = 10 / 2;
This behavior is a good reminder of PHP’s flexibility with integers and underscores the importance of understanding number systems in programming. Here are some tips to avoid confusion:
012
might come from legacy code or external sources and could cause bugs.According to the PHP manual on integers, PHP supports these number systems because they’re common in various programming and data contexts. This allows PHP developers to work easily with different numerical representations.
Key takeaways:
42
).0
(012
, equivalent to 10
in decimal).0x
(0x2A
, equivalent to 42
in decimal).0b
(0b101010
, equivalent to 42
in decimal).The next time you see a leading zero in PHP, take a closer look. It might just be an octal number in disguise! Understanding how PHP handles integers can save you from debugging headaches and help you write better, more predictable code.