<?php function g($a, $u = []) { $r = []; $size = sizeof($a); for ($i = 0; $i < $size; $i++) { if (empty($u[$i])) { $u[$i] = true; $vs = g($a, $u); $r[] = [$a[$i]]; foreach($vs as $v) { $r[] = array_merge(array( $a[$i] ) , $v); } $u[$i] = false; } } return $r; }