PHP
Generating All Possible Permutations of a PHP Array
Discover how to generate every unique ordering (permutation) of elements within a PHP array, a useful technique for algorithmic problems.
<?php
function generatePermutations(array $elements): array {
if (count($elements) <= 1) {
return [$elements];
}
$permutations = [];
foreach ($elements as $index => $element) {
$remainingElements = $elements;
array_splice($remainingElements, $index, 1); // Remove current element
foreach (generatePermutations($remainingElements) as $permutation) {
array_unshift($permutation, $element); // Add current element to front
$permutations[] = $permutation;
}
}
return $permutations;
}
$items = ['A', 'B', 'C'];
$allPermutations = generatePermutations($items);
/*
$allPermutations will contain:
[
['A', 'B', 'C'],
['A', 'C', 'B'],
['B', 'A', 'C'],
['B', 'C', 'A'],
['C', 'A', 'B'],
['C', 'B', 'A']
]
*/
?>
How it works: This recursive function calculates all possible orderings (permutations) of elements in an array. It works by taking each element in turn, removing it from the array, and then recursively generating permutations of the remaining elements. The chosen element is then prepended to each of these sub-permutations, and the results are accumulated.