0
$example1 = array(3, 9, 5, 12);
$example2 = array(5, 4);
$example3 = array(8, 2, 4, 7, 3);

How can I get combination one to one between these array elements without repetition?

For $example1 should return:

3 9
3 5
3 12
9 5
9 12
5 12

$example2:

5 4

$example3:

8 2
8 4
8 7
8 3
2 4
2 7
2 3
4 7
4 3
7 3

I tried:

<?php 

$example3 = array(8, 2, 4, 7, 3);

foreach ($example3 as $e) {

  foreach ($example3 as $e2) {
     if ($e != $e2) {
        echo $e . ' ' . $e2 . "\n"; 
     }
  }

}

This return me: http://codepad.org/oHQTSy36

But how is the best way to exclude repetition?

adarsh hota
  • 327
  • 11
  • 23
dakajuvi
  • 3
  • 3

2 Answers2

0

Almost. But in the second loop you need to pick just part of the original array.

array_slice function might be helpful here.

$example1 = array(3, 9, 5, 12);

for ($i = 0, $n = count($example1); $i < $n; $i++) {
    foreach(array_slice($example1, $i+1) as $value) {
        echo $example1[$i] . ' ' . $value . "\n";
    }
}
matewka
  • 9,912
  • 2
  • 32
  • 43
0

This just another way to get your result.

for($i=0;$i<count($example1);$i++)
{
    for($j=$i;$j<count($example1);$j++)
    {
        if($example1[$i] != $example1[$j])
        {
            echo $example1[$i].'::'.$example1[$j].'<br>';
        }
    }
}
AkshayP
  • 2,141
  • 2
  • 18
  • 27