glenelkins Posted March 13, 2009 Share Posted March 13, 2009 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 ) ); } } Quote Link to comment https://forums.phpfreaks.com/topic/149231-random-selection-problem/ Share on other sites More sharing options...
JonnoTheDev Posted March 13, 2009 Share Posted March 13, 2009 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]; Quote Link to comment https://forums.phpfreaks.com/topic/149231-random-selection-problem/#findComment-783670 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.