Skip to content

Instantly share code, notes, and snippets.

@neojoda
Created July 8, 2022 13:25
Show Gist options
  • Save neojoda/fe6f576d99a3b0a3c8add3e52f34fd64 to your computer and use it in GitHub Desktop.
Save neojoda/fe6f576d99a3b0a3c8add3e52f34fd64 to your computer and use it in GitHub Desktop.
[PHP] Calculate all the possible subsets given an array of elements
<?php
/**
* This is a function run recursevly to calculate all the possible subsets given an array
**/
function getAllSubsets($nums, &$result){
for ($i = 0; $i<count($nums); $i++)
{
$val = $nums[$i];
$result = ($result == " " ? $result.$val : $result." ".$val);
if ($i != 0){
for ($j=0;$j<=$i; $j++)
{
$val = $nums[$j];
if ($j==0){
$valInner = $val;
}
else
{
$valInner = $valInner.",".$val;
}
}
$result .= " ".$valInner;
}
}
array_shift($nums);
if (count($nums) > 0){
getAllSubsets($nums, $result);
}
}
$result=" ";
$nums = ['1','2','3', '4'];
getAllSubsets($nums, $result);
print_r (explode(" ", $result));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment