PHP – Random Numbers

Hello Readers,

I would like to tell u about generating random numbers in PHP. Random numbers are pretty useful when you want to randomly pick a case. Consider you have to display ten recent blog posts of a certain category. You have a bunch of images to display as featured image. From the bunch of images you have to pick them randomly. In this case, random numbers are so helpful. You can name the images in numbers, say 1.jpg to 100.jpg.

Now generate a random number from 1 to 100 and set a image to a blog post. You can refer to the following code.

<?php 
    foreach($blog as $post){
        $rand = rand(1, 100);
        $img = "<img src='".$rand.".img'/>";
        echo $post["title"];
        echo $img;
        echo $post["desc"];
    }
?>

But what if you get the same number generated twice or thrice. Numbers are random, so you would get any number, any number of times. Consider number 5 is generated thrice. You will get the same image thrice in the page and it doesn’t looks pleasant for the reader.

In order to avoid this situation, in order to avoid the repetition while generating random numbers, follow the following code.

<?php
     $rand = range(1, 20);
     shuffle($rand);
     $i=0;
     foreach($blog as $post){
        $img = "<img src='".$rand[$i].".img'/>";
        echo $post["title"];
        echo $img;
        echo $post["desc"];
        $i++;
     }
?>

In the above example we have used two array function, as their name implies – range function generates array value within specified range and shuffle function shuffles the array value.

Now we will get random numbers but without repetition.

Thanks for Reading.

Nagarajan
Follow me

Nagarajan

Web Developer at Energy Alternatives India
I'm interested in developing Web applications andkeen on learning new technologies.

View Nagarajan's Profile
Nagarajan
Follow me

Latest posts by Nagarajan (see all)

Comments
  1. due date calculator
    • Nagarajan

Leave a Reply

Your email address will not be published. Required fields are marked *