Php > Miscellaneous Code Examples

Multiple Unique Random Numbers

``` Multiple Unique Random Numbers <?php # Multiple Unique Random Numbers # # array mrand ( int min, int max, int count [, int strlen ] ) function mrand(\$l,\$h,\$t,\$len=false){ if(\$l>\$h){\$a=\$l;\$b=\$h;\$h=\$a;\$l=\$b;} if( ((\$h-\$l)+1)<\$t || \$t<=0 )return false; \$n = array(); if(\$len>0){ if(strlen(\$h)<\$len && strlen(\$l)<\$len)return false; if(strlen(\$h-1)<\$len && strlen(\$l-1)<\$len && \$t>1)return false; do{ \$x = rand(\$l,\$h); if(!in_array(\$x,\$n) && strlen(\$x) == \$len)\$n[] = \$x; }while(count(\$n)<\$t); }else{ do{ \$x = rand(\$l,\$h); if(!in_array(\$x,\$n))\$n[] = \$x; }while(count(\$n)<\$t); } return \$n; } ## Samples ## if(!\$numbers = mrand(1000,9999,10,4))die("error"); // 20 random, all 7 chars in length # \$numbers = mrand(0,9999999,20,7); // 20 random, length doesn't matter # \$numbers = mrand(0,9999999,20); # \$numbers = mrand(8000,10000,1,5) // ok # \$numbers = mrand(8000,10000,2,5) // error # \$numbers = mrand(120,100,20); // ok # \$numbers = mrand(100,120,21); // ok # \$numbers = mrand(120,100,21); // ok # \$numbers = mrand(120,100,22); // error # \$numbers = mrand(100,120,22); // error # \$numbers = mrand(120,120,1); // ok # \$numbers = mrand(120,120,2); // error # \$numbers = mrand(120,120,0); // error # \$numbers = mrand(1000000,9999999,3000); // Sort the array # sort(\$numbers); // Display the array echo '<pre>'; print_r(\$number); echo '</pre>'; ?> ```