Permutations in PHP.

/ Published in: PHP
Save to your folder(s)

A recursive function to permute the items of an array. The function returns an array that contains many arrays, where each array is a permutation of the original array. This process can get intensive depending on how many items are in the initial array and how big the array items are.

Copy this code and paste it in your HTML
  1. function permute(&$arr) { // permute the items in an array (n items, n at a time)
  2. static $perms = array(); static $usedItems = array();
  3. for ($i = 0; $i < sizeof($arr); $i++) {
  4. $item = array_splice($arr, $i, 1); //take item out
  5. $usedItems[] = $item[0];
  6. if (sizeof($arr) == 0) { // we have one permutation
  7. $perms[] = $usedItems; // add the result to our results container
  8. }
  9. permute($arr);
  10. array_splice($arr, $i, 0, $item[0]); //put item back
  11. array_pop($usedItems);
  12. }
  13. return $perms; // $perms contains arrays, each a permutation of the original array.
  14. }

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.