1

I am trying for 2 days to create a function to get all possible array combinations (without order repetitions):

 public function power_set($array) {
    // initialize by adding the empty set
    $results = array(array( ));

    foreach ($array as $element)
        foreach ($results as $combination)
            array_push($results, array_merge($combination,array($element)));

    return $results;
}

$keys = array(0=>1,1=>2,3=>3,21=>4,4=>5,5=>6,6=>7,7=>8,9=>10,10=>23,11=>34234,12=>34234,13=>34234,14=>45435,15=>32343,16=>35324,17=>4535345,18=>5645645,19=>234,20=>23324);

 echo '<pre>'.print_r(power_set($keys),true).'</pre>';

It work fine for a 7 element array, but more than than it dont't. How can I fix it?

John Mark
  • 3
  • 5
  • what output you want? – Deenadhayalan Manoharan Mar 18 '15 at 11:48
  • you want to remove duplicate? – Deenadhayalan Manoharan Mar 18 '15 at 11:48
  • I want all possible combinations of array values – John Mark Mar 18 '15 at 11:49
  • @DanyalSandeelo BTW: OP gets a notification if you post an answer, so no need for this comment ^. And for your information and for the future: http://meta.stackoverflow.com/a/253835/3933332 – Rizier123 Mar 18 '15 at 11:55
  • @JohnMark Can you please add your current output and your expected output. (Maybe with a smaller array :D) – Rizier123 Mar 18 '15 at 12:06
  • for array(1,2,3); I want a output of array(1),array(2),array(3),array(1,2),array(1,3), array(2,3) and array(1,2,3). Try my funtion, it will work. Just dont work with big sets. Maybe I ll slice the array. – John Mark Mar 18 '15 at 12:09
  • The array you give as parameter of the function is messy, can you explain what is it? Anyway for large arrays it gives me a fatal error: `Allowed memory size of 2097152 bytes exhausted (tried to allocate 64 bytes) on line 7` (array_push() function) – Phate01 Mar 18 '15 at 13:01

1 Answers1

0

John I think this is more of an issue with where you are running the code. As some of the comments on your question indicate, the php shell where you are executing the function has a limited working memory.

I tested with an array length 10, and was returned 1024 items (the correct amount).

Try running it as a file in your console: $ php test_file.php

tblumer3
  • 1
  • 1
  • I ll try. But try it with 20 or 30 elements. It will be a lot of repetitions and maybe it will run out of memory. I am trying to find a way to resolve it, maybe with array_chunk and dividing the loop jobs with different calls. – John Mark Mar 18 '15 at 14:24
  • Yeah, broke around 18-ish for me... What are you trying to do here anyway? You should reformat your question to make it clear that this is a working memory problem and not a program functionality issue. – tblumer3 Mar 18 '15 at 17:38