Jordan Savant # Software Engineer

Combinations of Array

This is a simple algorithm that produces (what I think) to be the different combinations of elements in an array:

<?php

$list = [1, 2, 3];

$combs = [];

for ($z = 0; $z < count($list); $z++) {

    for ($i = 0; $i < count($list); $i++) {
        $comb = [$list[$i]];

        for ($j = $i; $j < count($list); $j++) {
            if ($i == $j) continue;

            $comb[] = $list[$j];
        }

        if (count($comb) < count($list) || $z == 0) {
            sort($comb);
            $combs[] = $comb;
        }
    }

    array_push($list, array_shift($list));
}

print_r($combs);