PHP取多个不重复的随机数PHP取多个不重复的随机数
[php] view plaincopy
- function multi_rand($begin, $end, $count)
- {
- $rand_array = array();
- if ( $count > ($end - $begin + 1)) {
- $count = ($end - $begin + 1)
- }
- for ($i = 0;$i < $count; $i++ ) {
- $is_ok = false;
- $num = 0;
- while(!$is_ok){
- $num = rand($begin,$end);
- $is_out = 1;
- foreach ( $rand_array as $v) {
- if ( $v == $num ) {
- $is_ok = false;
- $is_out = 0;
- break;
- }
- }
- if ($is_out == 1) {
- $is_ok = true;
- }
- }
- $rand_array[] = $num;
- }
- return $rand_array;
- }
- //test
- print_r(multi_rand(1, 10, 8));