Finding All Element Combinations of an Array


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function pc_array_power_set($array) {
  2. // initialize by adding the empty set
  3. $results = array(array( ));
  4.  
  5. foreach ($array as $element)
  6. foreach ($results as $combination)
  7. array_push($results, array_merge(array($element), $combination));
  8.  
  9. return $results;
  10. }
  11. This returns an array of arrays holding every combination of elements, including the empty set. For example:
  12. $set = array('A', 'B', 'C');
  13. $power_set = pc_array_power_set($set);
  14. $power_set contains eight arrays:
  15. array( );
  16. array('A');
  17. array('B');
  18. array('C');
  19. array('A', 'B');
  20. array('A', 'C');
  21. array('B', 'C');
  22. array('A', 'B', 'C');

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.