Skip to content

Instantly share code, notes, and snippets.

@gwainor
Last active August 29, 2015 14:08
Show Gist options
  • Save gwainor/0d8c049d3680b983f8b1 to your computer and use it in GitHub Desktop.
Save gwainor/0d8c049d3680b983f8b1 to your computer and use it in GitHub Desktop.
This function is a recursive iterator function that gets all "unique" combinations with the given items.
<?php
function subsetSumRecursive($numbers, $arraySize, $level = 1, $i = 0, $addThis = [])
{
if ($level == $arraySize) {
$result = [];
for (; $i < count($numbers); $i++) {
$result[] = array_merge($addThis, array($numbers[$i]));
}
return $result;
}
$result = [];
$nextLevel = $level + 1;
for (; $i < count($numbers); $i++) {
$newAdd = array_merge($addThis, array($numbers[$i]));
$temp = subsetSumRecursive($numbers, $arraySize, $nextLevel, $i, $newAdd);
$result = array_merge($result, $temp);
}
return $result;
}
$numbers = [1, 2, 3, 4, 5, 6, 7];
echo "<pre>";
print_r(subsetSumRecursive($numbers, 7));
echo "</pre>";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment