I know this is a very old post, but the other answer is not very flexible, so I thought I would bring a new answer.
Explanation
, , :
(2 n) - 1
:
(2 3) - 1 = (8) - 1 = 7
, ? , ( , " " ($results = [[]];)), .
Array with the words/numbers (Empty array is '[]'):
[1, 2, 3]
//βnew combinations for the next iteration
β
iteration 0:
Combinations:
- [] β -> []
β
iteration 1: βββββββββββββββ€
β β
Combinations: v v
- [] + 1 β -> [1]
β
iteration 2: βββββββββββββββ€
β β
Combinations: v v
- [] + 2 β -> [2]
- [1] + 2 β -> [1,2]
β
iteration 3: βββββββββββββββ€
β β
Combinations: v v
- [] + 3 β -> [3]
- [1] + 3 β -> [1,3]
- [2] + 3 β -> [2,3]
- [1,2] + 3 β -> [1,2,3]
//^ All combinations here
, , : (2^n)-1 . , , array_filter(), array_values(), .
<?php
$str = "how are you";
function getCombinations($array) {
$results = [[]];
foreach ($array as $k => $element) {
foreach ($results as $combination)
$results[] = $combination + [$k => $element];
}
return array_values(array_filter($results));
}
$arr = getCombinations(explode(" ", $str));
foreach($arr as $v)
echo implode(" ", $v) . "<br />";
?>
:
how
are
how are
you
how you
are you
how are you