proud Posted October 19, 2009 Share Posted October 19, 2009 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? Quote Link to comment https://forums.phpfreaks.com/topic/178198-solved-need-help-in-generating-combinations/ Share on other sites More sharing options...
Daniel0 Posted October 19, 2009 Share Posted October 19, 2009 <?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"). Quote Link to comment https://forums.phpfreaks.com/topic/178198-solved-need-help-in-generating-combinations/#findComment-939538 Share on other sites More sharing options...
proud Posted October 19, 2009 Author Share Posted October 19, 2009 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? Quote Link to comment https://forums.phpfreaks.com/topic/178198-solved-need-help-in-generating-combinations/#findComment-939565 Share on other sites More sharing options...
JAY6390 Posted October 19, 2009 Share Posted October 19, 2009 foreach($combinations as $value) { echo implode(' ', $value).'<br />'; } Quote Link to comment https://forums.phpfreaks.com/topic/178198-solved-need-help-in-generating-combinations/#findComment-939568 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.