PHP

Generate All Permutations of an Array

Learn to generate every possible ordered arrangement (permutation) of elements within a given PHP array using a recursive backtracking algorithm, useful for combinatorial problems.

<?php
function generatePermutations(array $elements): array
{
    if (count($elements) <= 1) {
        return [$elements];
    }

    $allPermutations = [];
    foreach ($elements as $index => $element) {
        $remainingElements = $elements;
        array_splice($remainingElements, $index, 1); // Remove current element

        $subPermutations = generatePermutations($remainingElements);

        foreach ($subPermutations as $subPermutation) {
            $allPermutations[] = array_merge([$element], $subPermutation);
        }
    }
    return $allPermutations;
}

$items = ['A', 'B', 'C'];
$permutations = generatePermutations($items);

// foreach ($permutations as $permutation) {
//     echo implode(', ', $permutation) . "
";
// }
// Expected output for ['A', 'B', 'C']:
// A, B, C
// A, C, B
// B, A, C
// B, C, A
// C, A, B
// C, B, A
?>
How it works: This function `generatePermutations` recursively calculates all possible ordered arrangements (permutations) of elements in an array. It iterates through each element, uses it as the "first" element, and then recursively finds permutations of the remaining elements. These sub-permutations are then combined with the chosen "first" element to build the complete set of permutations.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs