Return to Snippet

Revision: 32994
at October 5, 2010 06:58 by nextu


Initial Code
function pc_array_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(array($element), $combination));

    return $results;
}
This returns an array of arrays holding every combination of elements, including the empty set. For example: 
$set = array('A', 'B', 'C');
$power_set = pc_array_power_set($set);
$power_set contains eight arrays:
array( );
array('A');
array('B');
array('C');
array('A', 'B');
array('A', 'C');
array('B', 'C');
array('A', 'B', 'C');

Initial URL

                                

Initial Description

                                

Initial Title
Finding All Element Combinations of an Array

Initial Tags
array

Initial Language
PHP