Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get the combinations of words

Status
Not open for further replies.
Jul 28, 2011
167
NG
I have an array like this
Code:
$myArray = array('a', 'b', 'c');
I want to get all combinations like so
Code:
a b c
a c b
b a c
b c a
c a b
c b a
Notice it is only a combination of the individual elements in the array (no individuals or doubles).

Any ideas please


____________________
A Pessimist sees every calamity in every opportunity but an Optimist sees every opportunity in every calamity
Think about it.
 
you might look at the pear combinatorics class.

there are a number of ways to solve this. all involve nested loops and/or recursion.
 
@jpadie: Thanks, but after much work I was able to resolve it with a small function like so:
Code:
function fn_combine ($items, $perms = array ()){
   if (empty ($items)){
       echo join(" ", $perms);
   } else {
       for ($i = count ($items)-1; $i >=0; --$i){
            $newitems = $item;
            $newperms = $perms; 
            list ($foo) = array_splice($newitems, $i, 1);
            array_unshift($newperms, foo);
            fn_combine ($newitems, $newperms);
         }
     }
}

Thanks bro.

____________________
A Pessimist sees every calamity in every opportunity but an Optimist sees every opportunity in every calamity
Think about it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top