php possible combinations of arrays?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mojoinst
Forum Newbie
Posts: 2
Joined: Thu Jan 15, 2004 8:47 pm

php possible combinations of arrays?

Post by mojoinst »

hi all

ive got a problem that is giving me a headache trying to work out.

any help will be extremely appreciated!
here is an example:

$array_1 = array("a","b","c");
$array_2 = array("x","y","z");
$array_3 = array("hello","bob","cat", "mouse");

what i am trying to do is make an array with all the possible combinations of array's 1, 2 and 3

for example:
a, x, hello
a, y, hello
a, z, hello
a, x, bob
a, y, bob
etc ...


i need some sort of recursive function, as the amount of arrays will vary (sometimes 1, other times 3, maybe even 9).


any help would be very much appreciated!

thanks for your time,

mojoinst
User avatar
tecktalkcm0391
DevNet Resident
Posts: 1030
Joined: Fri May 26, 2006 9:25 am
Location: Florida

Post by tecktalkcm0391 »

you'll have to something like this:
Untested:

Code: Select all

$number_of_arrays = 3;

$array_1 = array("a","b","c"); 
$array_2 = array("x","y","z"); 
$array_3 = array("hello","bob","cat", "mouse"); 


$a1 = count($array_1);
$a2 = count($array_2);
$a3 = count($array_3);

for($a=0; $a<$number_of_arrays; $a){
    for($b=0; $b<$a1; $b++){
            for($c=0; $c<$b1; $c++){
                 for($d=0; $d<$c1; $d++){
                       $arrays[] = array("$array_1[$b]","$array_2[$c]","$array_3[$d]");
                }
            }
        }
    }
}
Don't Know if that will work, but its something.
Post Reply