Home >Backend Development >PHP Tutorial >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!