get all permutations of a php array Â using -'php,permutation,combinatorics'

Given a PHP array of strings, e.g.:

['peter', 'paul', 'mary']

How to generate all possible permutations of elements of this array? i.e.:

peter-paul-mary

peter-mary-paul

paul-peter-mary

paul-mary-peter

mary-peter-paul

mary-paul-peter

Â Â Â Â

Given a PHP array of strings, e.g.:

['peter', 'paul', 'mary']

How to generate all possible permutations of elements of this array? i.e.:

peter-paul-mary

peter-mary-paul

paul-peter-mary

paul-mary-peter

mary-peter-paul

mary-paul-peter

Â Â Â Â

0 votes

0 votes

```
function pc_permute($items, $perms = array()) {
if (empty($items)) {
echo 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);
pc_permute($newitems, $newperms);
}
}
}
$arr = array('peter', 'paul', 'mary');
pc_permute($arr);

0 votes

I needed something similar and found this post while looking. Landed up writing the following which does the job.

With 8 items it works fairly quickly (a bit quicker than the examples I found online), but go beyond that and the run time ramps up rapidly. If you only need to output the results it could be made quicker and the memory use reduced massively.

```
print_r(AllPermutations(array('peter', 'paul', 'mary')));
function AllPermutations($InArray, $InProcessedArray = array())
{
$ReturnArray = array();
foreach($InArray as $Key=>$value)
{
$CopyArray = $InProcessedArray;
$CopyArray[$Key] = $value;
$TempArray = array_diff_key($InArray, $CopyArray);
if (count($TempArray) == 0)
{
$ReturnArray[] = $CopyArray;
}
else
{
$ReturnArray = array_merge($ReturnArray, AllPermutations($TempArray, $CopyArray));
}
}
return $ReturnArray;
}
```

Note that the number of permutations is the factorial of the number of items in the array. For 3 items there are 6 permutations, for 4 there are 24, for 5 there are 120, for 6 there are 720, etc.

0 votes

This does what you need, in place, i.e. without allocating any additional memory. It stores the resulting permutations the $results array. I would guess that this is the fasted way to solve the task.

```
function computePermutations(&$array, &$results, $start_i = 0) {
if ($start_i == sizeof($array)-1) {
array_push($results, $array);
}
for ($i = $start_i; $i
```

```
```

```
```

```
```

```
```

```
```

```
```

```
```

```
```

```
```

```
```

...