Jump to content

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?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.