Displaying a random string of text with PHP

Simple PHP Script

Simple PHP Random String Script

Evening All.

So building on the unprecedented success of my previous post here is what many refer to as “the difficult second post” so bear with me as I try and move things forward.

Right, this post is about generating and displaying a random piece of text with PHP. You may have noticed on the sidebar there is a little question such as “Need some assistance Smuggling your elephants across the border?

These little questions always come attached with a link to a humorous item on amazon.co.uk complete with a nice affiliate cookie. I have to admit its not really my idea, I saw it on Sickipedia and pulled a Keith Chegwin and stole the idea for my own.

Anyway the main point is that the question is randomly selected from a pre-defined list then presented to you the visitor upon your arrival. Now of course this could be done in JavaScript but we all know JavaScript is the work of Satan and makes the baby Jesus cry and you don’t want to make the baby Jesus cry do you?

So the first thing to do is to create a php file that contains all of your randomly selectable lines and in the following format:

————————————————————————–

<?php
$rand[] = 'Text1';
$rand[] = 'Text2';
$rand[] = 'I think you get the idea';
?>
————————————————————————–

Then name the file randomstrings.php and upload it to the same location that you want the random strings to be shown, if you’re using WordPress then this will be the folder of your WordPress theme.

Then to top it off simply add the following bit of code wherever you want your random sentance to be displayed:
————————————————————————–

<?php
include('randomstrings.php');
$randn = rand(0,count($rand)-1);
echo ($rand[$randn]);
?>

————————————————————————–

And there you have it, randomly output text on every page load.
To add more sentences just add more in the randomstrings.php file.
Simple :D