get random value from a PHP array, but make it unique

后端 未结 9 1119
挽巷
挽巷 2020-12-16 19:44

I want to select a random value from a array, but keep it unique as long as possible.

For example if I\'m selecting a value 4 times from a array of 4 elements, the s

9条回答
  •  暖寄归人
    2020-12-16 20:29

    How about shuffling the array, and popping items off.

    When pop returns null, reset the array.

    $orig = array(..);
    $temp = $orig;
    shuffle( $temp );
    
    function getNextValue()
    {
      global $orig;
      global $temp;
    
      $val = array_pop( $temp );
    
      if (is_null($val))
      {
        $temp = $orig;
        shuffle( $temp );
        $val = getNextValue();
      }
      return $val;
    }
    

    Of course, you'll want to encapsulate this better, and do better checking, and other such things.

提交回复
热议问题