# Thread: all possible combinations from 2 arrays

1. ## all possible combinations from 2 arrays

ok, say i have these two arrays:
Code:
```0 = red
1 = blue```
and
Code:
```0 = small
1 = medium
2 = large```
i want code which generates something like this:
Code:
```0 = (red, small)
1 = (red, medium)
2 = (red, large)
3 = (blue, small)
4 = (blue, medium)
5 = (blue, large)```

2. Rough but it works
PHP Code:
``` <?phpheader('content-type: text/plain');function combinations (\$a, \$b) {    \$big   = (count(\$a) > count(\$b)) ? \$a : \$b;    \$small = (count(\$a) < count(\$b)) ? \$a : \$b;    \$r = array();    for (\$i = 0, \$bl = count(\$big); \$i < \$bl; \$i++) {        for (\$x = 0, \$sl = count(\$small); \$x < \$sl; \$x++) {            \$return[] = \$small[\$x] . ', ' . \$big[\$i];        }    }    sort(\$return);    return \$return;}\$a = array('red', 'blue');\$b = array('small', 'med', 'large');print_r(combinations(\$a, \$b)); ```

3. cool, thanks.

just wondering what is the purpose of the \$big \$small variables?
why not just use \$a \$b?

4. Well to cover all values you need to know which array is bigger to make sure the outer loop goes over it enough times tho I probably over complicated it it is rough....hmmm drawing broad

5. just tried it out, big small isn't needed.

here is my rewrite:
Code:
```function combinations(\$a,\$b) {
\$return = array();
foreach(\$a as \$a_value) {
foreach(\$b as \$b_value) {
\$return[] = \$b_value.', '.\$a_value;
}
}
return \$return;
}```

6. for a more understandable print_r output, swapping the a_value and b_value at the middle will group them more nicely.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•