dan k
dan k

Reputation: 159

Pair all elements of an array in all possible combinations php

I've done some searching all i could find is this unfortunately thats not exactly what i'm looking for.

My problem is, i have a list of user ids in an array that could vary in size from 0 to 30+ users.

looks somehting like:

$arr = array(1,2,3);

What i need is to be able to find all pairs possible with this users:

(1 - 2)
(1 - 3)

(2 - 1)
(2 - 3)

(3 - 1)
(3 - 2)

the idea is to be able to create contact lists on a messaging platform so each one has each other on their contact list.

the examples on the question linked above gives me repeating elements and i can't have repeating elements also don't need 3 elements pared together only 2.

Upvotes: 0

Views: 2422

Answers (1)

scrowler
scrowler

Reputation: 24406

You have two objectives from the way I see it:

  1. Display all possible pairs between a and b numbers
  2. Don't display the same combination twice

You can achieve this with two loops and by keeping track of what you've processed already:

$arr = range(1, 30);
$alreadyProcessed = array();

foreach ($arr as $first) {
    // Loop the array twice (as @Dagon mentioned)
    foreach ($arr as $second) {
        // Keep track of what you've already processed
        $combination = array($first, $second);
        // Sorting the numbers will ensure that 2 - 1 and 1 - 2 are the same
        sort($combination);
        // Ensure they aren't the same number and you haven't already processed them
        if ($first === $second || in_array($combination, $alreadyProcessed)) {
            continue;
        }
        // Output as per your example
        echo "($first - $second)" . PHP_EOL;
        // Add it to the list of what you've already processed
        $alreadyProcessed[] = $combination;
    }
}

NOTE: this kind of logic is bad. You're performing an exponential number of repetitions because you're looping an array inside a loop of the same array. This particular example will perform 30 to-the-power-of 30 repetitions (a big, big number of cycles). That's only with 30 entries. What happens if your user base grows to 10,000? Bye bye server.

Upvotes: 1

Related Questions