pureDesi Posted June 18, 2007 Share Posted June 18, 2007 I have an array, let's say it's values are ['A', 'B', 'C', 'D']. I want to list out all the possible combinations that can be achieved using these values so it would display something similar to A B C D AB BA BC BD CA CB CD DA DB DC ABC ABA ABD .... So on and so forth. I've been working on it for some time and can't even come up with an algorithm, can anyone please assist me? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/56007-finding-all-possible-combinations-of-array/ Share on other sites More sharing options...
Psycho Posted June 18, 2007 Share Posted June 18, 2007 It's not pretty, but it works. <?php function notLast() { global $tempArray, $values; $iterations = count($values); $testArray = array_reverse($tempArray); foreach ($testArray as $key => $value) { if ($value != ($iterations-1) ) { $testArray[$key]++; for ($i=$key-1; $i>=0; $i--) { $testArray[$i] = $testArray[$i+1] + 1; } $tempArray = array_reverse($testArray); return true; } $iterations--; } return false; } $values = array ( 'A', 'B', 'C', 'D'); $results = array(); for ($parts = 1; $parts<=count($values); $parts++) { $tempArray = array(); for ($i=0; $i<$parts; $i++) { $tempArray[$i] = $i; } do { $value=""; foreach ($tempArray as $index) { $value = $value . $values[$index]; } $results[] = $value; } while (notLast()); } echo "<pre>"; print_r($results); echo "</pre>"; ?> Quote Link to comment https://forums.phpfreaks.com/topic/56007-finding-all-possible-combinations-of-array/#findComment-276622 Share on other sites More sharing options...
btherl Posted June 18, 2007 Share Posted June 18, 2007 Try this on for size.. it doesn't generate them in the order you expect though. function make_list($array, $length) { return make_list_rec('', $array, $length); } function make_list_rec($prefix, $array, $length) { $ret = array(); $append = array(); foreach ($array as $a) { $ret[] = "$prefix$a\n"; if ($length === 1) continue; # Recurse $new_length = $length - 1; $new_prefix = $prefix . $a; $append = array_merge($append, make_list_rec($new_prefix, $array, $new_length)); } return array_merge($ret, $append); } $array = array('a', 'b', 'c'); var_dump(make_list($array, 3)); Quote Link to comment https://forums.phpfreaks.com/topic/56007-finding-all-possible-combinations-of-array/#findComment-276654 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.