2

If my loop runs 3 times, then the output is 0001,2,3, but I need

0001
0002
0003  

How do I get this output?

$i='0001';
foreach($test as $rows){
    echo $i; 
    echo '<br/>';
    $i++;
}
Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
Dev
  • 181
  • 12

3 Answers3

4

Use printf with a padding specifier, e.g.:

$test = range(1,11);

$i = 0;
foreach ($test as $rows) {
  printf("%04d<br/>\n", ++$i);
}

Output

0001<br/>
0002<br/>
0003<br/>
0004<br/>
0005<br/>
0006<br/>
0007<br/>
0008<br/>
0009<br/>
0010<br/>
0011<br/>

In this example, 04 is a padding specifier meaning that the number (d) is padded with maximum 4 zeroes.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
1

You can use str_pad()

$i = "0001";
for($j=0;$j<1000;$j++) {
  echo str_pad($i++, 4, '0', STR_PAD_LEFT);
  echo "<br/>";
}
phobia82
  • 1,257
  • 8
  • 10
0

You can cheat a little bit,

$i = "1";
$y = "000"; //Added this

while ($i < 4){
    echo $y . $i;
    $i++;
}

Basically you echo the 000 in front of the number each time.

Mitch
  • 1,173
  • 1
  • 10
  • 31
  • 2
    well.. if the loop runs more than 9 times the outcome will become something like '00010' which is probably not what OP wants. Ruslans answer is probably better suited for OPs needs. edit: well i just realized Ruslans answer will output 00010 as well. (edit2: not after his edit) – kscherrer Nov 30 '16 at 13:01
  • if ($i >= 10){Do something}. But u'r probably right :) – Mitch Nov 30 '16 at 13:02
  • Not a great solution. – The Onin Nov 30 '16 at 13:07
  • True, but it is one. Ruslans answer is best i think. – Mitch Nov 30 '16 at 13:08