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 splitti
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
$pair = array_chunk($ids, 2);
http://www.php.net/manual/en/function.array-chunk.php
Sweet solution, Nev Stokes! I changed the 'while' statement to avoid the loop from breaking when one of the values is 0:
$ids = array(0, 1, 2, 3, 4);
$out = array();
while ( !is_null( $item = array_shift($ids) ) ) {
foreach ($ids as $key=>$value) {
$out[] = array($item, $value);
}
}
Fixed from my initial jump-the-gun suggestion of array_chunk()
Try this instead:
$ids = array(1, 2, 3, 4);
$out = array();
while ($item = array_shift($ids)) {
foreach ($ids as $key=>$value) {
$out[] = array($item, $value);
}
}
Probably not the best solution
$ids = array(1,2,3,4);
$pairs = array();
foreach($ids as $key => $data){
foreach($ids as $subkey => $subdata){
if( $subkey != $key){
if(!in_array(array($subdata, $data) , $pairs) ){
$pairs[] = array($data, $subdata);
}
}
}
}
Anyway it works
$ids = array(1,2,3,4);
$result=array();
foreach($ids as $value_1)
{
foreach($ids as $value_2)
{
if($value_1 !=$value_2)
{
$result[]=array($value_1,$value_2);
}
}
}
echo "<pre>";
print_r($result);