Kit
Kit

Reputation: 105

How to find all possible order with array item

Here is an array.

$item = array('A', 'B', 'C', 'D');

I want to list all possible orders in this array like:

A
A,B
A,B,C
A,B,C,D
A,C
A,C,D
A,C,B
...
B,A
B,A,C
....

How can I do that?

Upvotes: 4

Views: 1680

Answers (2)

footy
footy

Reputation: 5911

The permutations you want to know can be accomplished through this algorithm and applying in a loop for the subsets.

Initialize the first permutation with <1 <2 ...

while there exists a mobile integer

find the largest mobile integer k

swap k and the adjacent integer it is looking at

reverse the direction of all integers larger than k

Refer to this question for more info

Upvotes: 2

Alex Pliutau
Alex Pliutau

Reputation: 21957

You can use this recursive function:

function recursive_permutations($items,$perms = array( ))
{
 static $list;
 if (empty($items)) {
  $list[] = join(',', $perms);
 } else {
  for ($i = count($items)-1;$i>=0;--$i) {
   $newitems = $items;
   $newperms = $perms;
   list($foo) = array_splice($newitems, $i, 1);
   array_unshift($newperms, $foo);
   recursive_permutations($newitems, $newperms);
  };
  return $list;
 };
}
$perms = recursive_permutations(array('A', 'B', 'C', 'D'));
echo '<pre>' . print_r($perms, true) . '</pre>';

Upvotes: 1

Related Questions