views:

167

answers:

5

I think I just encountered the strangest 'bug' I've ever encountered in my short developer life. It seems like I just can't assign the value eight to any variable. For exemple:

<?php
$seven = 07;
$eight = 08; //what's wrong here?
$sevenB = 7;
$eightB = 8;

echo $seven;
echo $eight;
echo $sevenB;
echo $eightB;
?>

The output is:

7078

The debugger in NetBeans tells me 0 is assigned to $eight, while the other variables are fine. If I remove the zeroes before the values, eight gets assigned, but as soon as this variable is used in a constructor, then it's replaced by zero again. WTF?

Here's my config: WAMP 2.0g, PHP 5.2.9, Apache 2.2.11, NetBeans 6.7.1. Disabling Xdebug (2.05) doesn't change a thing.

Who is responsible for this inconsistent behavior? How to fix this?

Thanks for your help!

+20  A: 

PHP treats numbers with a preceding 0 as an octal.

Re: PHP:Integers.

Robert Duncan
+6  A: 

if you prefix your numbers with a zero (0) they are interpreted as octal numbers. 7 is the highest octal number. there’s also 0x for hexadecimal numbers (up to 15/F)

how to fix: just don’t prefix with 0 ;)

knittl
+9  A: 

In PHP, a number that's prefaced by a zero is considered to be octal. Because octal (base 8) only has digits 0-7, 08 is invalid and treated as zero.

See this manual page for more information, and note the warning in the syntax section: "If an invalid digit is given in an octal integer (i.e. 8 or 9), the rest of the number is ignored."

<?php
var_dump(01090); // 010 octal = 8 decimal
?>
Daniel Vandersluis
A: 

If your looking to lead a number with zero (Like a month calendar) you could try something like this:

<?
   for ($num = 1; $num <= 31; $num++) {
   if($num<10)
      $day = "0$num"; // add the zero
   else
      $day = "$num"; // don't add the zero
   echo "<p>$day</p>";
?>

Looks like everyone else also stated that a number leading with zero is treated as Octal

Phill Pafford
Or more concisely: echo sprintf( '%02s', $num );
rooskie
A: 

(s)printf is the only right way to do that.