Beware the zero!

Published June 16th, 2006

A colleague just called me over with a bit of stumper. He’d created a hard-coded array of numbers (the reason isn’t really important) and was seeing some strange behaviour. The array looked something like this:

$foo = array
(
'a' => 01,
'b' => 02,
'c' => 03,
'd' => 04,
'e' => 05,
'f' => 06,
'g' => 07,
'h' => 08,
'i' => 09,
'j' => 10,
'j' => 11
 );

..and so on. A bit of a neatness freak, he’d put the redundant zero in front of the single-digit numbers so that they lined up neatly in his (monospace font) editor. But when he printed the array out, he saw:

Array
(
    [a] => 1
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [g] => 7
    [h] => 0
    [i] => 0
    [j] => 11
)

Strange…

Something struck me as odd about the fact the the numbers 01-07 were ok, but not 08 or 09. So on a hunch, I looked up how PHP handles octal (base eight) numbers and sure enough:

If you use the octal notation, you must precede the number with a 0 (zero)

[PHP:: Integers]

So PHP sees the leading zero and assumes it’s an octal number — and 08 and 09 are not valid values in octal. You learn something new every day!

Get a Trackback link

1 Comments

  1. Richard Davies on July 13, 2006

    Thanks for the blog post. I just encountered a similar issue with JavaScript today, and because I remembered reading your blog post a few days ago I was able to quickly identify the problem.

    It turns out JS treats numbers like PHP does. I was using the parseInt() function to convert several strings of numbers to integers. It worked fine for “01″ – “07″, but returned 0 for “08″ and “09″.

Leave a comment

Comment Policy: First time comments are moderated. Please be patient.

OpenID

Anonymous