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

1.1k views Asked by At

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.

3

There are 3 answers

0
AbraCadaver On BEST ANSWER

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;
}
0
mjohns On

Might not be the most efficient, but you'll get what you're looking for:

$first = array_rand($atletas);
$second = $first;

while($atletas[$second] == $atletas[$first])
{
    $second = array_rand($atletas);
}

return array($atletas[$first], $atletas[$second]);
0
RNK On

This one will be your function:

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

    $recall = false;
    foreach($atletas_new as $a){
        if($a[0] == $a[1]){
            $recall = true;
            break;
        }
    }
    if($recall){
        sortear_grelha($atletas);
    }
    else{
        return $atletas_new;
    }
}

Call that function:

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