Store Hours
Call Us
727-755-4410
Easy Random Number Generator in PHP
06
June

Ever needed to generate a random number? How about generating random codes? Well if so, we have a cool little script for you.

Using PHP, we can create a nice little custom function that will generate random number of any size needed, thus making it really dynamic.

Let’s begin.

First we need to create the function. I’m going to call mine random_code.

function random_code() {
}

To make the function more dynamic, we are going to add a $size argument to it. This will allow us to change the random number size without having to rewrite the code.

function random_code($size) {
}

Now we can start adding some magic. We will create a variable called $characters. We will add all the characters we want our code to use. My example will have numbers, but you could add letters if you wanted to.

function random_code($size) {
    $characters = "0123456789";
}

Next we need to create a variable to contain the code as we generate it. I’m going to use $code.

function random_code($size) {
    $characters = "0123456789";
    $code = "";
}

Now the fun part. Generating the random code. We will use a for loop and the built in PHP function called rand to make it all work.

function random_code($size) {
    $characters = "0123456789";
    $code = "";
    $length = strlen($characters);
    for ($i = 0; $i < $size; $i++) {
        $code .= $characters[rand(0, $length - 1)];
    }
}

We also added a $length variable to assist the the rand function.

In a nutshell, the loop will run as many times as the $size is set to. Each time the loop runs, it picks a random character from the $characters variable until the $size variable is complete.

Now the only thing left is to return the code. For that we add return $code.

The completed function:

function random_code($size) {
    $characters = "0123456789";
    $code = "";
    $length = strlen($characters);
    for ($i = 0; $i < $size; $i++) {
        $code .= $characters[rand(0, $length - 1)];
    }
    return $code;
}

To use this function, simply call:

$code = random_code(4);

This will generate a random code containing 4 numbers.

I hope this was helpful. It can be used for almost anything that requires a randomly generated code.