function printPermutations(array $items): void {
$perms = permutations($items);
foreach ($perms as $p) {
echo implode(" ", $p) . PHP_EOL;
}
}
function printCombinations(array $items): void {
$size = count($items);
for ($i = 1; $i <= $size; $i++) {
foreach (combinations($items, $i) as $ch) {
echo implode(" ", $ch) . PHP_EOL;
}
}
}
// Generate all permutations recursively
function permutations(array $items): array {
if (count($items) <= 1) {
return [$items];
}
$result = [];
foreach ($items as $i => $item) {
$rest = $items;
unset($rest[$i]);
foreach (permutations(array_values($rest)) as $perm) {
array_unshift($perm, $item);
$result[] = $perm;
}
}
return $result;
}
// Generate all combinations of given length
function combinations(array $items, int $pos): array {
if ($pos === 0) {
return [[]];
}
if (empty($items)) {
return [];
}
$result = [];
$first = array_shift($items);
// Include first
foreach (combinations($items, $pos - 1) as $combo) {
array_unshift($combo, $first);
$result[] = $combo;
}
// Exclude first
foreach (combinations($items, $pos) as $combo) {
$result[] = $combo;
}
return $result;
}
$input = ['a', 'b', 'c'];
echo "All permutations:" . PHP_EOL;
printPermutations($input);
echo PHP_EOL . "All combinations:" . PHP_EOL;
printCombinations($input);
/*
run:
All permutations:
a b c
a c b
b a c
b c a
c b a
c a b
All combinations:
a
b
a b
c
a c
b c
a b c
*/