David
David

Reputation: 551

Weird PHP behavior: won't assign the integer 8 to a variable

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!

Upvotes: 0

Views: 315

Answers (5)

Nick
Nick

Reputation:

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

Upvotes: 0

Phill Pafford
Phill Pafford

Reputation: 85358

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

Upvotes: 0

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94264

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
?>

Upvotes: 9

knittl
knittl

Reputation: 265638

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 ;)

Upvotes: 6

Robert Duncan
Robert Duncan

Reputation: 510

PHP treats numbers with a preceding 0 as an octal.

Re: PHP:Integers.

Upvotes: 20

Related Questions