没有内置函数,但你可以这样做:
- function randWithout($from,$to,array $exceptions) {
- sort($exceptions); // lets us use break; in the foreach reliably
- $number = rand($from,$to - count($exceptions)); // or mt_rand()
- foreach ($exceptions as $exception) {
- if ($number >= $exception) {
- $number++; // make up for the gap
- } else /*if ($number < $exception)*/ {
- break;
- }
- }
- return $number;
- }
这是我的头脑,所以它可以使用抛光 – 但至少你不能最终陷入无限循环的情况,甚至假设.
注意:如果$exceptions耗尽您的范围,则该函数会中断 – 例如调用randWithout(1,2,array(1,2))或randWithout(1,array(0,1,3))将不会产生任何明智的(显然),但在这种情况下,返回的数字将在$from- $到范围之外,所以它很容易被捕获.
如果保证$exceptions已被排序,则排序($exceptions);可以删除.