0

I'm looking to create a PHP Range loop

In a first and second number in the range, but have noticed the first number which is

00006

Is being rounded down / flattened to show "6".

So when I echo the first number value I get "6" back. I need it to be "00006"

Then the next number will need to be 00007 and so on, via the range loop.

My PHP code at present is :

$first_number = 00006;
$last_number = 11807;

foreach(range($first_number, $last_number) as $id)
{
  echo $id;
}

How do I go about making sure that the number has the previous 0's in it?

StuBlackett
  • 3,789
  • 15
  • 68
  • 113
  • you need to use some format function when echoing `$id`, [check this](https://stackoverflow.com/questions/1699958/formatting-a-number-with-leading-zeros-in-php). – Definitely not Rafal Nov 09 '20 at 10:40
  • Cheers @DefinitelynotRafal it looks like the number range is within 5 of that pad length, so that will do the trick – StuBlackett Nov 09 '20 at 10:45

1 Answers1

1

You can do it by using printf() function. See the documentation : printf

First of all in PHP, a number starting with zero is treated as octal number, But I guess range() function converts it as decimal. So if you want to start it with 20. Like $first_number = 00020; then the output will be start with 16 not 20.
So, if you want the output starting with 0's, then you can do like this:

$first_number = 6;
$last_number = 11807;

foreach(range($first_number, $last_number) as $id)
{
  printf("%05d",$id);
}

Anisur Rahman
  • 644
  • 1
  • 4
  • 17