Charles
Charles

Reputation: 11

Get 0 to 9999 in PHP using FOR EACH and Array?

How would I print all values 0...9999 using an array of $array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); ? No clue, please help.

Upvotes: 1

Views: 446

Answers (3)

mkoistinen
mkoistinen

Reputation: 7773

$array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

foreach ($array as $i) {
   foreach ($array as $j) {
      foreach ($array as $k) {
         foreach ($array as $l) {
            print $i*1000+$j*100+$k*10+$l."\n";
         }
      }
   }
}

Smells like a homework assignment ;)

Upvotes: 0

ontrack
ontrack

Reputation: 3043

This would seem like an homework assignment, so some thinking of your own should apply. Example below is specifically strict to the assignment, it is in no way the best solution for just displaying all number between 0 and 9999.

$array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

foreach($array as $value_1)
    foreach($array as $value_2)
        foreach($array as $value_3)
            foreach($array as $value_4)
                echo $value_1.$value_2.$value_3.$value_4.PHP_EOL;

Upvotes: 4

aularon
aularon

Reputation: 11110

<?php
$array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
foreach ($array as $a) {
  foreach ($array as $b) {
    foreach ($array as $c) {
      foreach ($array as $d) {

        if ($a) echo $a;
        if ($a || $b) echo $b;
        if ($a || $b || $c) echo $c;

        echo $d. "<br />\n";
      }
    }
  }
}

Upvotes: 0

Related Questions