Random content can make your web pages feel a bit more alive, it can also give the browsing experience for your visitors a bit of a boost. Luckily, random content is pretty easy to accomplish using PHP.
For this tutorial I'll use random quotes as an example. First of all, we need to setup an array of our quotes.
Now that we have our quotes, all we need to do is grab one out and echo it. If you remember from the Utilizing Arrays tutorial, all of our array items have keys, in this case, they are numerical keys. Meaning that if you were to do somthing like..
<?php
|
|
You would end up with the value of the the second item in the array. Remember array keys always start at 0, so 1 is the second item, not 2. Having said that, we can use the rand() function to generate a random number, which we will use to grab a random key from the array. Here's an example:
<?php
|
|
The code above will print one of the quotes in the $quotes array to the page. But wait, what happens if you add more quotes to the array? You'll need to edit the line that generates the random number, and increase the 2 by however many more quotes you added.
However, that can become annoying. So, instead, we're going to modify the rand() function call, and change the second parameter to automatically count the number of items in the array using count().
<?php
|
|
You might be wondering why I subtracted one from the total number of quotes. This is because, if you had 3 quotes in an array, the highest key in that array is 2. So, in order to keep our random number from going over the number of our highest key, we just subtract one from the second parameter of the rand() function.
Now, if you put it all together, you come up with this:
That's it! Pretty simple, eh? Go ahead and test it out, play around with it. See what more you can add to it. When you're done, have a look at the second page, which will show how you can produce multiple random things, like I have done for my random affiliates box.
| Discuss Tutorial: Randomizing Content | 14 Comments |

.



