Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array into unique pairs

Tags:

arrays

php

Say i start with a simple array (which could be theoretically of any length):

$ids  = array(1,2,3,4);

What it the best solution for splitting this array into an array of unique pairs like:

$pair[0] = array(1,2);
$pair[1] = array(1,3);
$pair[2] = array(1,4);
$pair[3] = array(2,3);
$pair[4] = array(2,4);
$pair[5] = array(3,4);
like image 450
robjmills Avatar asked Sep 22 '10 14:09

robjmills


1 Answers

The simplest solution is to use a nested loop and build combinations as you go, although note that the complexity here is O(n2).

$ids = array(1,2,3,4,4);
$combinations = array();

$ids = array_unique($ids); // remove duplicates
$num_ids = count($ids);

for ($i = 0; $i < $num_ids; $i++)
{
  for ($j = $i+1; $j < $num_ids; $j++)
  {
    $combinations[] = array($ids[$i], $ids[$j]);
  }
}

See this in action at http://www.ideone.com/9wzvP

like image 192
Daniel Vandersluis Avatar answered Sep 25 '22 06:09

Daniel Vandersluis