phparraysloopscombinations

Print unique pairs/combinations from a flat array of values


i have this array:

$um = array("PHP", "Python", "Java", "C++");

and i need something like this:

PHP ------- Python
PHP ------- Java
PHP ------- C++
Python ---- Java
Python ---- C++
Java ------ C++

so, i am trying:

for ($i = 0; $i < count($um); $i++) {
    for ($x = 1; $x < count($um); $x++) {
        echo $um[$i]."-----".$um[$x]."\n";
    }
}

but i get this output

PHP------Python
PHP------Java
PHP------C++
Python---Python
Python---Java
Python---C++
Java-----Python
Java-----Java
Java-----C++
C++------Python
C++------Java
C++------C++

Any idea how can i correct the loop ?


Solution

  • Change the value that $x is set to in your inner for loop from $x = 1 to $x = $i + 1

    for ($i = 0; $i < count($um); $i++) {
        for ($x = $i + 1; $x < count($um); $x++) {
            echo $um[$i]."-----".$um[$x]."\n";
        }
    }