Search code examples
phparrayssplitchunks

How to split an array into pairs of different elements in PHP randomly?


Example:

$atletas = array("A", "B", "C", "D", "E", "Bye", "Bye", "Bye");

My function:

function sortear_grelha($atletas) {
        shuffle($atletas);
        $atletas = array_chunk($atletas, 2);
        return $atletas;
}

Expected result for example:

[["A","Bye"],["C","Bye"],["Bye","D"],["B","E"]]

The output I am getting:

[["A","Bye"],["Bye","Bye"],["C","D"],["B","E"]]

I want pairs of different values.


Solution

  • Here's one that works by calling sortear_grelha() recursively until there are no duplicates in a pair:

    function sortear_grelha($atletas) {
            shuffle($atletas);
            $result = array_chunk($atletas, 2);
    
            if(array_map('array_unique', $result) != $result) {
                return sortear_grelha($atletas);
            }
            return $result;
    }