Max0999
Max0999

Reputation: 354

PHP random every hour

My php is rusty, I am trying to get a PHP code to return a different user ID's added to the following array from an array of possible users.

'online_users'            => array(54)
'bots_ids'                => array(153,122,173,124,173,132,184,188)

I want to pick and a add random bot every 1-5 hours after which he will be replaced by another bot or just deleted (not all bots have to be online simutaniously)

I tried setting the seed to the current hours divided by a random number but it doesn't seem to work.

Thanks in advance!

Upvotes: 0

Views: 1320

Answers (2)

Ikstar
Ikstar

Reputation: 163

I think you are looking for a array_rand() in this case. It will select up to N random keys out of the array and place them in their own array. This will let you do what you're looking to do .

$online_bots = array('4','5','6');
$bot_ids = array('1','2','3');

$random_bots = array_rand($bot_ids,1); // Random id from list
$bot_going_offline = array_shift($online_bots); // pop a bot from online

$online_bots[]= $bot_ids[$random_bots]; // add random bot from list
$bot_ids[] = $bot_going_offline; // move the oldest online bot into common pool

As for the 2nd part of the question, you can setup cron to execute the script at every hour that would trigger the change. Alternatively, to Online/Offline List you can just have a common pool of bots that gets randomly picked every hour.

$num_bots = rand ( 0, count($bot_ids));
$random_bots = array_rand($bot_ids,1); // Random id from list
for ($x = 0; X< $num_bots; x++)
   $online[] = $bot_ids[$random_bots[$x]];

Upvotes: 1

Baba
Baba

Reputation: 95101

A. You can use cron job to call your script every hour ... to get the random bots can be easily done with array_rand

$bots = array(153,122,173,124,173,132,184,188);
$current = $bots[array_rand($bots)];
var_dump($current);

B. If yout have a continues loop you should look at How to echo something every 4 minutes while in an endless loop and replace echo with your random selector

Upvotes: 0

Related Questions