Rotating quotes in PHP
I added some random quotes to the top right of this blog (go ahead and refresh!). Since I’m using Wordpress I decided to go with a PHP version instead of javascript. In a nutshell the differences between PHP and JS:
Anyone can use the JavaScript version. It will run on any blog that allows the use of scripts. It will also run on static, non-blog websites. For any blogging system that does not use PHP, like Blogger, it’s the only choice.
If you’re using a system like WordPress, there are advantages to the PHP version. The biggest of these is that PHP is server-side and JavaScript is not. The JavaScript version will download everything and a visitor’s web browser runs the script to determine what to display. Because of this, your visitor’s browser must be able to run JavaScript for anything to happen. Some devices, like mobile phones and other small-screen browsers, don’t support JavaScript at all.
PHP works differently. The PHP script runs on the web server, so only the output is sent to the web browser. In addition to saving you a marginal amount of bandwidth, this guarantees that all viewers will see the content properly.
If you can use PHP, there’s not really any reason at all to use the JavaScript version.
Here is the code but just like with the JavaScript version, the script generates no HTML, so you’ll need to wrap the script in whatever tags are appropriate for your situation:
PHP Version:
<?php
$myRandomQuotes=array(
'quote 1 goes here.',
'quote 2 goes here.',
'quote 3 goes here.',
'quote 4 goes here.'
);
echo $myRandomQuotes[rand(0,sizeof($myRandomQuotes)-1)];
?>
note: To prevent the apostrophes in “You’re” and “Don’t” etc. from screwing up everything, I added in a backslash to tell the JavaScript interpreter to treat the next character as text rather than a command.