PHP School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!
 

Code Snippets

  

PHP Source Code



Random Number Generator

Created for my lottery site, originally. Generate x random numbers, no repeats, from number 1-x. Uses random.org for "real" random numbers, if random.org fails to load for some reason it resorts to php's built-in rand() function.

Submitted By: ShaneK
Actions:
Rating:
Views: 2,062

Language: PHP

Last Modified: September 19, 2009
Instructions: 1) Insert into Code
2) Call like normal function
3) Enjoy

Snippet


  1. function create_sequence($tickets){
  2.         $array = @file("http://www.random.org/sequences/?min=1&max=".$tickets."&col=1&format=plain&rnd=new"); //Uses random.org to generate "real" random numbers
  3.         if(is_array($array)){
  4.                 foreach($array as $data){
  5.                         $winners[] = (int)preg_replace('#([^\d])#', '', trim($data)); //Stores the numbers in the array (numbers only)
  6.                 }
  7.         }
  8.         if(!is_array($winners) || count($winners) < $tickets){ //Basically, if random.org failed to load...
  9.                 $winners = array();
  10.                 while(count($winners) < $tickets){
  11.                         $number = rand(1, $tickets); //We use PHP to generate our own random numbers, which are "less random" than random.org
  12.                         if(!in_array($number, $winners)){
  13.                                 $winners[] = $number; //Assigns our own generated numbers to the array
  14.                         }
  15.                 }
  16.         }
  17.         return($winners); //Returns the "winners," basically the new random number array.
  18. }

Copy & Paste


Comments

There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.