I have always wanted to have a simple Random Title Generator for some of my sites because it would be something rather fun. I know of many Javascript-based ones, but it would 1) Give away how I did it and 2) It would not work on some browsers. So, That has always persuaded me not to do it. Until I saw a nameless site touting it and would not give away how it worked. Well, Now I know how it works and now it is my time to share.
First things first, you need to create some titles (about 7 to start, but you can add later on) and they all have to be different. Got them? Good.
Putting Titles into an Array
Now, you have to learn about arrays. Using arrays allows one to list something or create something that would use the arrays to show data using different switches. If already know what arrays are, then you can continue to read, however, if you do not know what arrays are, then read This first.
For this script, I will be using an array called title. This Array is just like an variable, but it has ordered data. So, now that we are ready, lets create our array.
PHP Tutorials :
<?
$title = array("I want to go to Hawyee .... Yay!!!", "You think Metallica is cool??? Shame on you!!!!!",
"Young Nasty Man can produce Mind Bullets ... What can you do?", "Mmmm .... Twinkies",
"Eat Twinkies, Be Merry", "I've got mail ... YAY!!!!", "Welcome!!");
?>
Now, as you can see, I made an array with 7 titles and they are separated by commas. The use of arrays cut down on size, so, instead of having 7 different variables, I have 1 array and less space.
Randomizing it and printing it
Now, we have to use rand() to do the whole random part of the script.
PHP Tutorials :
<?
$number = rand(1, 7);
?>
This will now enable the script to choose between 1 and 7 and it will continue to do so every time it is accessed. Sweet huh?
Ok, all we have to do is print the nice new title.
PHP Tutorials :
<?
print "$title[$number]";
?>
End your PHP page and finish up
Finishing it up In the title of your page that you want to randomize the title for, put the following code:
PHP Tutorials :
<?
include "randomtitle.php";
?>
And you have a random title. For those of you who want to know more ... the array is a bunch of static info (unless you were to grab some of the info from an SQL database) and the array itself is not dynamic. What makes it dynamic is rand(). It dynamically chooses what number should be printed. From there it is rather easy and it can be finished/printed and it is done.