3

I'm doing a for loop to count from 0001 up to 0999

How can i do this with php. All i've got so far is a normal php for loop.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Exoon
  • 1,513
  • 4
  • 20
  • 35

5 Answers5

8

Something like this?

for($i = 1; $i<=999; $i++){
    echo str_pad($i, 4, '0', STR_PAD_LEFT);
}

Additionally, you can make use of sprintf() instead of str_pad(), but I think str_pad() looks much clearer than sprintf() in this case.

Christian
  • 27,509
  • 17
  • 111
  • 155
6

What you want to do is a normal loop and format the output:

for( $i=1; $i<=999; $i++) {  
  $myformat = str_pad($i, 4, '0', STR_PAD_LEFT);         
  // do something with $myformat
}
JvdBerg
  • 21,777
  • 8
  • 38
  • 55
3

Try that code:

for($n=1;$n<=999;$n++)
{
    $formatted_n = str_pad($n, 4, '0', STR_PAD_LEFT);
    // add some code here
}

Documentation for str_pad

Jocelyn
  • 11,209
  • 10
  • 43
  • 60
0
<?php

for($i=1; $i<=999; $i++) {
 echo str_pad($i, 4, "0", STR_PAD_LEFT);
}

?>
sarsnake
  • 26,667
  • 58
  • 180
  • 286
0

Here is a version using sprintf():

foreach (range(1, 999) as $i){
  echo sprintf("%04d", $i); 
} // output: 000100020003...
jon
  • 5,986
  • 5
  • 28
  • 35
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` in any code for any reason -- it should be `printf()` without `echo` every time. – mickmackusa Apr 09 '22 at 02:27