0

I have a string like: 00030000 and need to increment this with loop.

$start = "00030000";

for ($i = 1; $i < 10; $i++) {
    echo $i + $start;
}

It prints this

30001 
30002 
30003 
30004 
//...

This is understood but how can I get following result?

00030001 
00030002 
00030003 
00030004 
//...
Rizier123
  • 58,877
  • 16
  • 101
  • 156
Umair A.
  • 6,690
  • 20
  • 83
  • 130
  • 1
    Also, it may be off-topic. but be aware that in PHP `030` is not `30`, but `24`. This is because PHP threats numbers starting with a 0 as octals (except when the 0 is followed with a decimal point). – Christian Aug 14 '12 at 22:26
  • Why does not `echo "000", $i + $start;` work for you? You always have three zeroes in front if you look closely. Just take care of the formatting with the output, not the calculation. – hakre Aug 14 '12 at 22:26
  • @hakra this is one case where the starting number has padded zeros. Many other may not. – Umair A. Aug 14 '12 at 22:32

5 Answers5

2

Zero pad it to your required length using str_pad

$start = "00030000";

for ($i = 1; $i < 10; $i++) {
    $sum = $i + $start;
    echo str_pad($sum, 8, "0", STR_PAD_LEFT);
}

Output:

00030001
00030002
00030003
...
sachleen
  • 30,730
  • 8
  • 78
  • 73
1

You can use strpad or sprintf to get this.

$input = "30";
echo str_pad($input, 4, "0", STR_PAD_LEFT);  // produces "0030"
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
1
$start = "00030000";
$startLen = strlen($start);
for ($i = 1; $i < 10; $i++) {
    echo str_pad($i + $start, $startLen, '0', STR_PAD_LEFT );
}
KadekM
  • 1,003
  • 9
  • 13
1

for fun:

$start = "00030000";
$start = '_' . $start;

for ($i = 1; $i < 100; $i++) {
    echo ltrim($start++, '_');
    echo "\n";
}

Please don't actually use that code. While it works perfectly and takes advantage of a documented feature of php, its bewildering to most people who would read it(which makes it bad code). Use one of the answers that uses str_pad()

goat
  • 31,486
  • 7
  • 73
  • 96
0
$start = "00030000";
for ($i = 1; $i < 10; $i++) {
    echo sprintf( "%08u\n", $i + $start );
 }
TerryE
  • 10,724
  • 5
  • 26
  • 48
  • `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 08 '22 at 16:29