Randomly Display Some Images From A Set of Images: PHP

Use of this script:
1. If you have a photo blog with 100 or more images, using this small php script you can show some random images on your homepage, to keep it more dynamic.. This makes up for a good user experience due to constant fresh content(images) each time.
2. If you have 10 products and you want to show atleast 3 products image on your homepage, using this php script you can randomly display the images and yet not bore your audience!

Video Tutorial: Randomly Display Some Images From A Set of Images: PHP



YouTube Link: https://www.youtube.com/watch?v=ajAj6oAkz60 [Watch the Video In Full Screen.]


Source Code: Randomly Display Some Images From A Set of Images: PHP

(image.php)



 
  Random Images
 
 
  
    \"$pic[$i]\" "; ?>

Copy and paste above code into a plain text editor. Save the file with .php file extension. Make sure to have 5 image files(with .jpg extensions) in the same folder as image.php

random-image


PHP Code Explanation:

Arrays are very important concept in all programming language.

 $pic = array('1.jpg','2.jpg','3.jpg','4.jpg','5.jpg');

here $pic is an array variable and is used to store the file names of all the images.

shuffle($pic);

shuffle() is a standard PHP function, which shuffles the content of the array variable. i.e., it re-orders or changes the position of the elements of an array.


                           \"$pic[$i]\"
                        ";
?>

Usually unordered listing tags of HTML displays elements vertically.

  • But using some css style property, we are showing the images horizontally.
    i.e., display: inline;

    for loop, loops through 0 to 3(in above example). After the execution of the above line of code(for one instance), we get the following HTML output in the browser.

    • 4
    • 5
    • 1

    \ (back slash) is used as an escape character, to escape the effect of (double quote).

    2 thoughts on “Randomly Display Some Images From A Set of Images: PHP”

    Leave a Reply

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