Andy
Andy

Reputation: 515

PHP Generate possible number with specific format

I need to generate possible number with some format/rule.

  1. 5 digit number
  2. first digit > 0

    for($x=0;$x=10;$x++) { $first=1;$second=0;$third=0;$fourth=0;$five=0;

    for($i=1;$i<10;$i++){ $first=$i; break; } for($i=0;$i<10;$i++){ $second=$i; break; } for($i=0;$i<10;$i++){ $third=$i; break; } for($i=0;$i<10;$i++){ $fourth=$i; break; } for($i=0;$i<10;$i++){ $five=$i; break; }

    echo $first.$second.$third.$fourth.$five.'\n'; }

desired result: 10000 10001 10002 ...until 99999

but seems broken :(

Upvotes: 0

Views: 43

Answers (1)

Sharanya Dutta
Sharanya Dutta

Reputation: 4021

Instead of using separate for loops you need to nest them inside one another:

for($i = 1; $i <= 9; $i++){
    for($j = 0; $j <= 9; $j++){
        for($k = 0; $k <= 9; $k++){
            for($l = 0; $l <= 9; $l++){
                for($m = 0; $m <= 9; $m++){
                    print("$i$j$k$l$m\n");
                }
            }
        }
    }
}

DEMO

But, obviously, a simpler approach would employ only one for loop:

for($i = 10000; $i <= 99999; $i++){
    print("$i\n");
}

DEMO

Upvotes: 3

Related Questions