Scroll To Top

I used to do a lot of contests where I select a random winner. Unlike the past I don't print out all of the contestants and draw from the hat, I use a command line PHP script.

Here is the file I use to draw random winners for my contests.

* Random Draw
* v1.0
* Last Updated: June 5, 2011
* URL:
* Each contastant must have a number (array starts at 1)

//Get number of entires
$contestants = $argv[1];
$winner = rand_best(1,$contestants);

$print = <<<EOTXT
And the winner is entry#: $winner \n

echo $print;

* Function from stack overflow
function rand_best($min, $max) {
    $generated = array();
    for ($i = 0; $i < 100; $i++) {
        $generated[] = mt_rand($min, $max);
    $position = mt_rand(0, 99);
    return $generated[$position];


All you need to do to run this is open the command line, navigate to the directory it is stored and run the command:

php name_of_file.php 100

where 100 is the number of contestants.

The interesting peice of this code is the function that shuffles the randomly generated numbers. The goal is to be a little closer to true random.