I am trying to create a function generate all the possible unique combinations of array elements.
As an example, my array is $inputs = [1,2,3,4,5]; and I want to create all the possible combinations of a particular size $size = 3;.
So the result of the combinations should be like the result array.
$result = [
[1,2,3],
[1,2,4],
[1,2,5],
[1,3,4],
[1,3,5],
[1,4,5],
[2,3,4],
[2,3,5],
[2,4,5],
[3,4,5]
];
I created this following function.
function getCombinations(array $inputs, $size) {
//$inputs = [1,2,3,4,5];
//$size = 3;
// if array length is equal to the input array size or size is larger than the array size
// there is only one combination
if (count($inputs) == $size || count($inputs) < $size) {
return $inputs;
}
$result = [];
$lastMostEndIndex = count($inputs) - 1;
$lastMostStartIndex = $lastMostEndIndex - (count($inputs) - $size);
$isHitLastMostEndIndex = false;
$startIndex = 0;
$endIndex = $size - 1;
// runs until last most end index is reached
while (!$isHitLastMostEndIndex) {
$subArray = [];
for ($i = $startIndex; $i <= $endIndex; $i++) {
$subArray[] = $inputs[$i];
}
// pusing the combination to result array
$result[] = $subArray;
$startIndex++;
$endIndex++;
if ($endIndex > $lastMostEndIndex) {
$isHitLastMostEndIndex = true;
}
}
return $result;
}
But this function only returns
$result = [[1,2,3],[2,3,4],[3,4,5]];
I think I need to add more loops but I can not figure it out.
Can someone please give me a hand or point me how to get all the unique combinations out of this function?