mankee mankee - 6 months ago 10
PHP Question

Copying x random values from one array to another PHP

I'm trying to copy 5 random values from one array to another with the following code. The problem is 3 or 4 values get copied and 1 or 2 are always copied as

null
. I'm not sure what the problem in my code is.

if (count($potential_matches_in_area) >= 5) {
for ($x = 0; $x < 5; $x++) {

$index = mt_rand(0, count($potential_matches_in_area) - 1);
$new_matches[$x] = $potential_matches_in_area[$index];
unset($potential_matches_in_area[$index]);

}

Answer

The problem is, this line:

mt_rand(0, count($potential_matches_in_area) - 1);

You can get duplicate keys, the first time it runs, it runs okay, but once the unset key reappears again, you'll get an undefined index. Why not just use array_rand instead.

if (count($potential_matches_in_area) >= 5) {
    for ($x = 0; $x < 5; $x++) {
        $index = array_rand($potential_matches_in_area);
        $new_matches[$x] = $potential_matches_in_area[$index];
        unset($potential_matches_in_area[$index]);
    } 
}

You'll only get the present keys thats still available.