random
PHP Script To Select A Person To Make The Tea
Mon, 04/06/2009 - 10:05 | by philipnorton42In any office there can be arguments about who will make the next round of tea. The following script will allow you to randomly pick a person who is going to make the tea. Rather than have a script that did this once and threw away the information I thought it would be a good idea to use cookies to save the form data for the next time you want to pick a person to make the tea. This is a good exercise if you are trying to understand how cookies work.
First, we will need to variables, the first is an array of people and the second is the number of people in the office.
Randomise JavaScript Array
Fri, 07/04/2008 - 08:43 | by philipnorton42Randomising a JavaScript array can be done in one or two ways. The easy way is to create a function that returns a random number and then use the sort() function of the Array object to sort the array by a random value.
Generate A Random Colour With PHP
Wed, 05/21/2008 - 08:35 | by philipnorton42Here is a short bit of code to generate a random hexadecimal colour using PHP. Essentially you just create a random number between 0 (000000) and 10,000,000 (ffffff) and turn this into a hexadecimal number using the PHP function dechex.
$colour = rand(0, 10000000); $colour = dechex($colour);
This can also be accomplished on a single line.
$colour = dechex(rand(0, 10000000));
Random Number Range In MySQL
Sat, 04/05/2008 - 19:35 | by philipnorton42To create a number between one value and the next you can use the following formula, where i is the lower end of the range and j is the higher end of the range.
FLOOR(i + RAND() * (j – i))
Rather than put in (j-i) in your query you should put in the result. So for a number between 1 and 10 you would make i = 1 and j = 11. 11-1 = 10 so the query would run like this.
Shuffle An Array In PHP
Thu, 01/24/2008 - 11:38 | by philipnorton42To randomise an array in PHP use the shuffle() function like this.
$array = range(1,5); shuffle($array); // randomise array
There are two limitations to this function. The first is that it completely removes any key association that you may have set up. So the following array.
$array = array('one'=>1,'two'=>2);
Would be turned into the following after using shuffle().
Getting A Random Row From A PostgreSQL Table
Thu, 01/10/2008 - 09:50 | by philipnorton42To get a random row from a PostgreSQL database you need to use the RANDOM() function. This is similar to the MySQL function RAND() and will generate a new random number for each row and order them by that new number. This is used in conjunction with the LIMIT clause to limit the amount of returned rows to one.
SELECT value FROM table ORDER BY RANDOM() LIMIT 1