Jump to content

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];

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.