Home >Backend Development >PHP Tutorial >How Can I Efficiently Generate All Unique Subsets of an Array in PHP?

How Can I Efficiently Generate All Unique Subsets of an Array in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-22 08:46:10306browse

How Can I Efficiently Generate All Unique Subsets of an Array in PHP?

Finding Subsets of an Array in PHP

The task of finding unique subsets of an array can be particularly challenging when dealing with a large number of elements. We seek to create a comprehensive set of subsets, ensuring no repetition occurs.

For instance, given an array of attributes {A, B, C, D}, we want to generate all possible subsets, including individual elements and their combinations: {A, B, C, D, AB, AC, AD, BC, BD, CD, ABC, ABD, BCD, ABCD}.

Using Array Merge for Power Set Generation

PHP provides a compact solution for power set generation utilizing the array_merge function.

function powerSet(array $array) : array {
    $results = [[]];

    foreach ($array as $element) {
        foreach ($results as $combination) {
            $results[] = [...$combination, $element];
        }
    }

    return $results;
}

// Example usage:
$ATTRIBUTES = ['A', 'B', 'C', 'D'];
$SUBSETS = powerSet($ATTRIBUTES);

The resulting $SUBSETS array will contain all non-repeating subsets of the original array.

The above is the detailed content of How Can I Efficiently Generate All Unique Subsets of an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn