Michael
Michael

Reputation: 1886

PHP Combination Of Arrays

Edit: A little background on this. We have a module that accepts 6 different variables. We are looking at trying to completely automate the testing and fine tuning of the possible different values that the module accepts.

I have 6 arrays and need to get the combinations of all the possibilities.

$words[1] = array("A","B","C","D","E","F");
$words[2] = array("Aa","Bb","Cc","Dd","Ee","Ff");
$words[3] = array("Aq","Bq","Cq","Dq","Eq","Fq");
$words[4] = array("Ab","Bc","Cd","De","Ef","F");
$words[5] = array("Az","Bz","Cz","Dz","Ez","Fz");
$words[6] = array("A1","B1","C1","D1","E1","F1");

So basically I am looking for every possible unique combination, while still maintaining the order of the $words array.

Examples:

C Bb Fq De Bz B1

C Bb Fq De Bz E1

C Bb Fq De Fz B1

Upvotes: 0

Views: 204

Answers (2)

Ben D
Ben D

Reputation: 14489

xdazz has the right approach, but the wrong execution... you need to create a single string:

$ret = array();
foreach ($words[1] as $word1) {
  foreach ($words[2] as $word2) {
    foreach ($words[3] as $word3) {
      foreach ($words[4] as $word4) {
        foreach ($words[5] as $word5) {
          foreach ($words[6] as $word6) {
            $ret[] = $word1.' '.$word2.' '.$word3.' '.$word4.' '.$word5.' '.$word6;
          }
        }
      }
    }
  }
}
print_r($ret);

Upvotes: 1

Runar Jørgensen
Runar Jørgensen

Reputation: 544

This should give you the desired output.

for($a=0; $a < count($words[1]); $a++) {
  for($b=0; $b < count($words[2]); $b++) {
    for($c=0; $c < count($words[3]); $c++) {
      for($d=0; $d < count($words[4]); $d++) {
        for($e=0; $e < count($words[5]); $e++) {
          for($f=0; $f < count($words[6]); $f++) {
            echo $words[1][$a] . " " . $words[2][$b] . " " . $words[3][$c] . " " . $words[4][$d] . " " . $words[5][$e] . " " . $words[6][$f] . "<br />";
          }
        }
      }
    }
  }
}

Upvotes: 1

Related Questions