Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

4.24. Finding All Element Combinations of an Array

Problem

You want to find all combinations of sets containing some or all of the elements in an array, also called the power set .

Solution

Use the pc_array_power_set( ) function shown in Example 4-5.

Example 4-5. pc_array_power_set( )

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');

Discussion

First, you include the empty set, {} , in the results. After all, one potential combination of a set is to take no elements from it.

The rest of this function relies on the nature of combinations and PHP’s implementation of foreach. Each new element added to the array increases the number of combinations. The new combinations are all the old combinations alongside the new element; a two-element array containing A and B generates four possible combinations: {}, {A}, {B}, and {A, B}. Adding C to this set keeps the four previous combinations but also adds four new combinations: {C}, {A, C}, {B, C}, and {A, B, C}.

Therefore, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata