Skip to content

Instantly share code, notes, and snippets.

@RyanNutt
Created July 4, 2021 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyanNutt/80d3071b1d5b3f7ec3b7d9b4df232009 to your computer and use it in GitHub Desktop.
Save RyanNutt/80d3071b1d5b3f7ec3b7d9b4df232009 to your computer and use it in GitHub Desktop.
Get all permutations of an array in PHP - from https://stackoverflow.com/a/24517966/1561431
<?php
function computePermutations($array) {
$result = [];
$recurse = function($array, $start_i = 0) use (&$result, &$recurse) {
if ($start_i === count($array)-1) {
array_push($result, $array);
}
for ($i = $start_i; $i < count($array); $i++) {
//Swap array value at $i and $start_i
$t = $array[$i]; $array[$i] = $array[$start_i]; $array[$start_i] = $t;
//Recurse
$recurse($array, $start_i + 1);
//Restore old order
$t = $array[$i]; $array[$i] = $array[$start_i]; $array[$start_i] = $t;
}
};
$recurse($array);
return $result;
}
$results = computePermutations(array('foo', 'bar', 'baz'));
print_r($results);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment