Return to Snippet

Revision: 45302
at April 28, 2011 07:37 by trusktr

Initial Code
function permute(&$arr) { // permute the items in an array (n items, n at a time)
		static $perms = array(); static $usedItems = array();
		for ($i = 0; $i < sizeof($arr); $i++) {
			$item = array_splice($arr, $i, 1); //take item out
			$usedItems[] = $item[0];
			if (sizeof($arr) == 0) { // we have one permutation
				$perms[] = $usedItems; // add the result to our results container
			array_splice($arr, $i, 0, $item[0]); //put item back
		return $perms; // $perms contains arrays, each a permutation of the original array.

Initial URL

Initial Description
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.

Initial Title
Permutations in PHP.

Initial Tags

Initial Language