skip to Main Content

I am trying to generate 4 digit sequential numbers starting from any given number. Where I am stuck is keeping the leading 0’s as I’ll need 4 digits all the time. Here is my code.

$start = '0520';
for($i = 0; $i <= 100; $i++) {
    echo ($start + $i) . ',';
}

It gives me output like this..

520,521,522,523,524,525,526,527,528,529,530,531,532, and so on..

Therefor I tried several answers here in SO, but the nearest I reached is having 5 digits number with this

$start = '0520';
for($i = 0; $i <= 100; $i++) {
   echo sprintf('%05d', ($start + $i)) . ',';
}

It outputs 5 digit sequential numbers starting with 00520.

What would be the best way to generate 4 digit sequential numbers keeping the leading 0’s?

Thanks

2

Answers


  1. Try this

    $start = 520;
    $generatedNumbers = [];
    for ($i = 0; $i <= 100; $i++) {
        $generatedNumbers[] = '0' . $start+$i;
    }
    
    print_r($generatedNumbers);
    
    Login or Signup to reply.
  2. Solution, very easy, is to use

    echo sprintf('%04d', ($start + $i)) . ',';
    

    I think you missed 04 😀

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search