How to iterate over a loop for numbers starting with 0 in PHP?

I am trying to iterate with a for loop through 8 digits starting from 0. For example, the first number: 00000000 , and I would like to display the next 5 numbers. So far, I have succeeded. eg:

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

Everything is fine there with this example, but problems begin with this 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 creates:

 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 

when 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 
+5
source share
2 answers

This does not work because numbers starting with 0 are interpreted as octal numbers. On the Entire PHP Documentation Pages (Emphasis mine) page :

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

Binary integer literals are available since PHP 5.4.0.

To use octal notation, 0 (zero) follows the number . Use hexadecimal notation precedes the number with 0x. Use binary notation precedes number with 0b.

Just use:

  $start = 50200; 

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

+9
source

The reason you get other numbers is because the leading zero makes your octal number. So, you start by setting $start = 00050200; making $start octal.

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

+2
source

Source: https://habr.com/ru/post/1260649/


All Articles