I'm currently developing a theme, and I'm new to the coding/programming side of web development (I'm a graphic designer, and want to learn to be a programmer!), and want to have the feature of a randomly rotating image as part of my theme's header. Currently I have 6 different images from which to choose, but would like to know how to actually get them to change on their own (either upon login or upon refresh).
I looked up both an HTML and PHP version of how to do this... the HTML version looks way too longwinded to be the most efficient way of doing this, but I don't understand the PHP version.
$file = rand(1, 20);
$file .= '.jpg';
echo '<img src="'.$file.'" >';
I know that $file is a variable. I am assuming I'd have to set that in the template.php.tpl. The rest of the stuff... I'm not understanding b/c I'm just learning the basics of PHP.
Comments
Here's a breakdown,
Here's a breakdown, line-by-line.
$file = rand(1, 20);This call to the function rand() generates a random number between 1 and 20, and assigns it to the variable
$file. For this example, let's say rand() gives you the value 6. Then $file would have the value 6.$file .= '.jpg';This appends the string '.jpg' to the variable
$filethat we generated above. In our example,$filewould now have the value '6.jpg'.echo '<img src="'.$file.'" >';The echo command prints variables, and/or whatever is inside quotes (strings). Variables and strings can be concatenated with the dot operator '.' and then the entire result can be printed out with the echo command. Here we are concatenating three things: a string, a variable ($file), and a string, and then printing them out. Variables are evaluated before printing, so for our example, the line above decomposes to
echo '<img src="' . '6.jpg' . '" >';. When the strings are concatenated this line decomposed further intoecho '<img src="6.jpg" >';, which upon execution prints out the HTML for displaying image 6.jpg.This example you provided assumes you have 20 images with the names 1.jpg, 2.jpg, 3.jpg, ..., 20.jpg. If you want to use only six images, then you would change the first line to read
$file = rand(1, 6);. Furthermore, each of your files would need to be named 1.jpg, 2.jpg, 3.jpg, ..., 6.jpg. You would most assuredly also need to add more to the first string in the the third line of code to make sure that the img tag references the correct path to the location of the images.You would then insert this code in the page template (most likely page.tpl.php). Since this template already has the <?php delimiters, you don't need to add them; you only need to add the actual three lines of code.