PHP取多个不重复的随机数



PHP取多个不重复的随机数PHP取多个不重复的随机数

  1. function multi_rand($begin, $end, $count)
  2. {
  3.                 $rand_array = array();
  4.                 if ( $count > ($end - $begin + 1)) {
  5.                          $count = ($end - $begin + 1)
  6.                 }
  7.                 for ($i = 0;$i < $count; $i++ ) {
  8.                         $is_ok = false;
  9.                         $num = 0;
  10.                         while(!$is_ok){
  11.                             $num = rand($begin,$end);
  12.                             $is_out = 1;
  13.                             foreach ( $rand_array as $v) {
  14.                                 if ( $v == $num ) {
  15.                                     $is_ok = false;
  16.                                     $is_out = 0;
  17.                                     break;
  18.                                 }
  19.                             }
  20.                             if ($is_out == 1) {
  21.                                 $is_ok = true;
  22.                             }
  23.                         }
  24.                         $rand_array[] = $num;
  25.                 }
  26.        return $rand_array;
  27. }
  28. //test
  29. print_r(multi_rand(1, 10, 8));