V
V
Vyacheslav Leonov2016-01-18 15:15:41
PHP
Vyacheslav Leonov, 2016-01-18 15:15:41

How to select unique combinations from an array?

I have an array, for example:

$array = array('orange', 'apple', 'banana', 'pine');

You need to get all the unique combinations from it.
That is, it should look like this:
array('orange', 'apple');
array('orange', 'banana');
array('orange', 'pine');
array('orange', 'apple', 'banana');
array('orange', 'apple',  'pine');
array('apple', 'banana');
array('apple', 'pine');
array('apple', 'banana', 'pine');
array('banana', 'pine');

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Cat Anton, 2016-01-18
@LastRide

One of the many solutions:
stackoverflow.com/questions/4279722/php-recursion-...

$a = array('orange', 'apple', 'banana', 'pine');

$len  = count($a);
$list = array();

for ($i = 1; $i < (1 << $len); $i++) {
    $c = [];
    for ($j = 0; $j < $len; $j++) {
    	if ($i & (1 << $j)) {
            $c[] = $a[$j];
    	}
    }
    $list[] = $c;
}

print_r($list);

ideone.com/YE9BII

N
Nicholas, 2016-01-18
@healqq

Mm ... in fact, the task is reduced to building an enumeration + checking the occurrence of an element in a set.
To check, it is worth defining some function that associates an array with a certain string (in fact, some kind of hashing function), and the string will be unique for each possible array.
Then the uniqueness can be controlled by checking the unique strings of the current value that already exist in some array.

O
Optimus, 2016-01-18
Pyan @marrk2

At first we will clean up
Then we will make a cycle in a cycle and by search for each value of an array we will substitute the others. In the process, add it to a new array. Ready.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question