Skip to content
Advertisement

Randomly Show an HTML Snippet From List With PHP

As the title implies, I have a few different lines of HTML code (Example Below), and I would like the server to randomly select one and show it when the page loads.

I have these three HTML snippets, and I want one to randomly show when the page is loaded.

<img src=“image1.png” alt=“image1”>
<p class=“class1”>Image Caption<a href=“link1”> And Link</a></p>
<img src=“image2.png” alt=“image2”>
<p class=“class2”>Image Caption<a href=“link2”> And Link</a></p>
<img src=“image3.png” alt=“image3”>
<p class=“class3”>Image Caption<a href=“link3”> And Link</a></p>

I found this example using the PHP array function, but I don’t know how to put the array in a separate PHP file, or if I can change the image links to full HTML code.

The example I found:

<?php
    $images = array('img1.jpg', 'img2.jpg', 'img3.jpg');
?>

Then, you just get a random element from the array

<?php
    $random_image = array_rand($images);
?>

Then you can go right away displaying the image:

<img src="<?php echo $images[$random_image]; ?>" />

How can I make this so the HTML snippets above are stored in the array, and the array is in a different PHP file (I can use the “require” function for that, right?).

Advertisement

Answer

You can echo any amount of html code just like you would echo the value of a property.

You’re right that you can use require to access an array defined in another file.

<?php
    $images = require 'images_array.php';
    echo $images[array_rand($images)];
?>

images_array.php:

array(
    '<img src=“image1.png” alt=“image1”><p class=“class1”>Image Caption<a href=“link1”> And Link</a></p>',
    '<img src=“image2.png” alt=“image2”><p class=“class2”>Image Caption<a href=“link2”> And Link</a></p>',
    '<img src=“image3.png” alt=“image3”><p class=“class3”>Image Caption<a href=“link3”> And Link</a></p>',
);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement