3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $facts = []; function fact($N, &$facts) { if ($N<=1) { return 1; } if (!array_key_exists($N, $facts)) { $facts[$N] = $N * fact($N - 1, $facts); } return $facts[$N]; } function C($n, $k, &$facts) { return fact($n, $facts) / fact($k, $facts) / fact($n - $k, $facts); } function combination ($index, $k, $A, $facts) { $res = [0]; $n = sizeof($A); $s = 0; for ($t = 1; $t <= $k; $t++) { $j = $res[$t - 1] + 1; while (($j < ($n - $k + $t)) && (($s + C($n - $j, $k - $t, $facts)) <= $index)) { $s += C($n - $j, $k - $t, $facts); $j++; } $res[] = $j; } array_splice($res, 0, 1); print_r($res); } $m = [1,2,3,4,5]; for ($i = 0; $i < C(sizeof($m), 3, $facts); $i++) { combination($i, 3, array_slice($m, 0), $facts); }
based on urA2e
Output for 5.6.0 - 7.3.0alpha1
Array ( [0] => 1 [1] => 2 [2] => 3 ) Array ( [0] => 1 [1] => 2 [2] => 4 ) Array ( [0] => 1 [1] => 2 [2] => 5 ) Array ( [0] => 1 [1] => 3 [2] => 4 ) Array ( [0] => 1 [1] => 3 [2] => 5 ) Array ( [0] => 1 [1] => 4 [2] => 5 ) Array ( [0] => 2 [1] => 3 [2] => 4 ) Array ( [0] => 2 [1] => 3 [2] => 5 ) Array ( [0] => 2 [1] => 4 [2] => 5 ) Array ( [0] => 3 [1] => 4 [2] => 5 )