Hyperion
Hyperion

Reputation: 909

Random array, showing less than 3 of the same

I am using a random PHP array for a raffle type script and I sometimes get the same string 3 or more times. How can I limit the random to only show a max of 2 of the same string?

For example I have:

  <?php
  $raffle = array('string1', 'string2', 'string3', 'string4', 'string5', 'string6');

  echo $raffle[array_rand($raffle)] . ", " . $raffle[array_rand($raffle)] . ", " .   $raffle[array_rand($raffle)] . ", " . $raffle[array_rand($raffle)];
  ?>

So it chooses a random of 4 strings from the array, but I don't want the same string to show up more than twice. How can I achieve this?

Upvotes: 1

Views: 138

Answers (1)

Damien Black
Damien Black

Reputation: 5647

Below is a function that will store what has been pick, and if picked again, remove it from the array. Once removed from the array, it'll never get picked again. So items can show up twice, but not more:

function pull_raffle() {
    static $raffle = array('string1', 'string2', 'string3', 'string4', 'string5', 'string6');
    static $pulled_before = array();

    $pick = array_rand($raffle);
    $string = $raffle[$pick];
    if (array_key_exists($string, $pulled_before)) {
        unset($raffle[$pick]);
    } else {
        $pulled_before[$string] = true;
    }

    return $string;
}

Use it like this:

echo pull_raffle() . ", " . pull_raffle(). ", " .  pull_raffle() . ", " . pull_raffle();

Upvotes: 1

Related Questions