2 Easy PHP scripts for beginners.
Die Roller
There is almost no difference between rolling a six-sided die and picking a random number between 1 and 6. In PHP, this is simple: echo rand(1,6);
PHP provides a random number generator: mt_rand(). It is safe to assume that mt_rand is a faster and is an overall better random number generator, With that, It is: echo mt_rand(1,6);
Using the mt_rand() random number-generator function
function roll () { return mt_rand(1,6); } echo roll();
Now we can pass the type of die we want to roll as a parameter to the function, as seen here.
function roll ($sides) { return mt_rand(1,$sides); } echo roll(6); // roll a six-sided die echo roll(10); // roll a ten-sided die echo roll(20); // roll a twenty-sided die
From here, you can roll multiple dies at once and have a lot of sides. But overall, A very simple script for most tasks.
Lotto Picker
Let's put together a script that lets us keep track of lotto winning numbers and shoots out the six least-picked numbers in our list.
We save winning lotto picks in a text file. We separate numbers by comma and put each set of numbers on its own line. When we get the file contents, go ahead and split on newlines, and split each line on commas.
Saving winning lotto picks in a text file
$picks = array( array('6', '10', '18', '21', '34', '40'), array('2', '8', '13', '22', '30', '39'), array('3', '9', '14', '25', '31', '35'), array('11', '12', '16', '24', '36', '37'), array('4', '7', '17', '26', '32', '33') );
Obviously that is not much of a base for drawing stats. but its enough to show the principles.
So we must set a base array to hold the range of number picking. For example, if we pick numbers from 1 to 20 (e.g., $numbers = array_fill(1,20,0);, then walk through our picks, putting in appropriate matching values.
Walking through our picks
foreach ($picks as $pick) { foreach ($pick as $number) { $numbers[$number]++; } }
At last, sort out the numbers based on value. This should then have the least-picked numbers at the front of the array.
Sorting the numbers based on value
asort($numbers); $pick = array_slice($numbers,0,6,true); echo implode(',', array_keys($pick));
By regularly and frequently adding actual lotto picks to the text file containing our list of picks, we can trend number-picking over the long term. It's interesting to see how much some numbers come up.