Jump to content

Random Selection Problem


glenelkins

Recommended Posts

Hi

 

Im having a frustrating issue with a function written to select a random player from an array. The function checks with another array to see if its been used already.

 

All this is doing is causing a time out error. Here is an example:

 

$players_array could be like $players[0] = 1; $players[1] = 2; etc

 

function random_player ( $players_array, $used_players ){ 

    $total_players = count ( $players_array );

    foreach ( $players_array as $key => $id ) {

        do {

             $random_player_pos = rand ( 0, $total_players -1 );

        } while ( in_array ( $players_array[$random_player_pos], $used_players ) );

    }

}

 

           

Link to comment
https://forums.phpfreaks.com/topic/149231-random-selection-problem/
Share on other sites

Your probably creating an infinate loop here. Also your methodology is wrong.

If you want to return a player number that hasn't already been used then your function should do the following

 

1. Take in both arrays

2. Remove all players from the players array that are in the used players array

3. Obtain a random player from the players array

 

You will never get a used player as there will be none to select from. Also use array_rand() to return a random array key:

 

// give me 1 player at random
$player = array_rand($players_array, 1);
return $players_array[$player];

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.