Jump to content

[SOLVED] Need help in Generating Combinations


proud

Recommended Posts

Need help generating all possible combination of names in an array

 

Lets say i have the following array:

 

$names = array("jack","john","Adam","Mike");

 

Now my goal is to find all possible combination of 2 names (first name and second name)

 

e.g.  Jack John , Jack Adam, Jack Mike etc...

 

 

So how can I do this with PHP?

 

<?php
$names = array("jack","john","Adam","Mike");

$numNames = count($names);
$combinations = array();
foreach ($names as $name1) {
$n1 = array_shift($names);
foreach ($names as $name2) {
	$combinations[] = array($n1, $name2);
}
}

print_r($combinations);

 

Assuming order is irrelevant (i.e. "Jack John" is the same as "John Jack") and that a person cannot be combined with himself (e.g. "Jack Jack").

Yes its solved,the output looks like this:

Array ( [0] => Array ( [0] => jack [1] => john ) [1] => Array ( [0] => jack [1] => Adam ) [2] => Array ( [0] => jack [1] => Mike ) [3] => Array ( [0] => john [1] => Adam ) [4] => Array ( [0] => john [1] => Mike ) [5] => Array ( [0] => Adam [1] => Mike ) ) 

 

 

just one last thing, I'm trying to get rid of the array keys => which appear in the output, so i tried something like this:

 

<?php
$names = array("jack","john","Adam","Mike");

$numNames = count($names);
$combinations = array();
foreach ($names as $name1) {
   $n1 = array_shift($names);
   foreach ($names as $name2) {
      $combinations[] = array($n1, $name2);
   }
}


foreach ($combinations as $key => $combination) {
   if ($key > 0) { echo ', '; }
   echo $combination.' ';
} 

?>

 

still couldn't solve the problem, any ideas?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.