Random php block

Hi,

I’m trying to find a simple way to do the below:

  • I have a php page and have a small div that contains some content, <h2><p> etc

  • I want to have various different versions of that div content, store the different content in an external file or includes or something and call it in selecting the different content randomly on refresh.

Any help would be great. I would like to stick to php rather than javascript if possible.

Merci x

Here is the simplest way of doing it.

random_divs.php


<?php

$divs = array(
'<h2>Div one</h2><p>content one</p>',
'<h2>Div two</h2><p>content two</p>',
'<h2>Div three</h2><p>content three</p>',
);


mypage.php


// some html


<?php
include 'random_divs.php';

echo $divs[array_rand($divs)];
?>

// more html

Total legend, thanks so much cups! works a treat, Happy Xmas!

Thanks! Same to you.

I suppose that if those divs became ginormous in size, then you could ech divs in their own file and include just the random one.

untested

random_div_3.php


<h2>Random Three</h2>
<p>Content three</p>

mypage.php


// some html

<?php
$max = 10;
include 'random_divs_' . rand(1, $max) . '.php';
?>

// more html

You’d probably put the files in their own folder though. (eg: /random_divs/1.php)

There are ways of simply adding files to a folder and your script picking one at random, so negating the need for maintaining a $max – another day, eh?