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
PHP for loop can be used to traverse set of code for the specified number of times. It should be used if the number of iterations is known otherwise use while loop. This means for loop is used when you already know how many times you want to execute a block of code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With