I have a website. On this website, I am trying to generate random images. The code for this looked messy when I had it mixed in with the rest of the HTML on the main page, so I decided to use an ‘include’ call to call another page with the php functions I wanted on it.
The problem with calling functions to run the specific blocks of code is, that when it runs, it doesn’t recognise that I have tried to put some global variables at the top, therefore when it outputs a number, there isn’t one because it never had one.
Can anybody tell me how I can fix this, so that I can use the variables so that they have the initial values I would like?
<?php
$total1 = "4";
$start = "1";
$random1 = mt_rand($start, $total1);
$total2 = "3";
$random2 = mt_rand($start, $total2);
function randomImage1()
{
$file_type = ".jpg";
$image_folder = "Images/Picturebar";
$image_name = $random1 . $file_type;
echo ("<img src=\"$image_folder/$image_name\" alt=\"$image_name\" width=\"204px\" height=\"100px\" />");
echo("$random1");
}
function randomImage2()
{
$file_type = ".jpg";
$image_folder = "Images/Picturebar";
if ($random2 == $random1) {
$random2 = $random2 + 1;
}
$image_name = $random2 . $file_type;
echo "<img src=\"$image_folder/$image_name\" alt=\"$image_name\" width=\"204px\" height=\"100px\" />";
echo("$random2");
}
?>
You need to reference the variables globally inside the functions, or better yet, pass them as parameters:
This could also be done with the
globalkeyword inside the function, but passing parameters as above is preferred: