5

I'm trying to iterate with for loop through 8 digit numbers starting with 0. For example, the first number is: 00000000 and I would like to display next 5 numbers. So far I managed to accomplish sth. like that:

<?php

     $start = 00000000;
     $number = 5;

     for ($i = $start; $i < $start + $number; $i++) {
        $url = sprintf("http://test.com/id/%08d", $i);
        echo $url . "\r\n";
     }
?>

Result:

http://test.com/id/00000000
http://test.com/id/00000001
http://test.com/id/00000002
http://test.com/id/00000003
http://test.com/id/00000004

There's everything fine with this example, however, problems start with such an example:

<?php

         $start = 00050200;
         $number = 5;

         for ($i = $start; $i < $start + $number; $i++) {
            $url = sprintf("http://test.com/id/%08d", $i);
            echo $url . "\r\n";
         }
    ?>

The for loop produces:

http://test.com/id/00020608
http://test.com/id/00020609
http://test.com/id/00020610
http://test.com/id/00020611
http://test.com/id/00020612

while I expect:

http://test.com/id/00050200
http://test.com/id/00050201
http://test.com/id/00050202
http://test.com/id/00050203
http://test.com/id/00050204
Peter
  • 215
  • 2
  • 13

2 Answers2

9

It doesn't work because numbers beginning with a 0 are interpreted as octal numbers. From the Integers page of the PHP Documentation (Emphasis mine) :

Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +).

Binary integer literals are available since PHP 5.4.0.

To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b.

Simply use :

 $start = 50200;

At the beginning of your code and everything should work fine.

roberto06
  • 3,844
  • 1
  • 18
  • 29
2

The reason you get other numbers is that a leading zero makes your number octal. So you start by setting $start = 00050200;, this makes $start octal.

Just remove these leading zeroes and the code will be fine.

Jerodev
  • 32,252
  • 11
  • 87
  • 108