wesley Posted October 3, 2015 Share Posted October 3, 2015 Hello, I have a question. I want to make a random image function with a array. When I refresh the webpage you see a another random image. It is required to use the php function mt_rand();. When I search on the internet I see the mt_rand accept only integers. Can someone give me advice how to fix this? Is it possible to convert int to image? The code is: function photorandom() { $photo = array("1.jpg", "2.jpg", "3.jpeg", "4.jpg"); $random = mt_rand(); echo "<img src="$photo" alt="">";}photorandom(); thanks in advance. Link to comment Share on other sites More sharing options...
Ingolme Posted October 3, 2015 Share Posted October 3, 2015 Use the integer that mt_rand() returns as the index of the array. Link to comment Share on other sites More sharing options...
dsonesuk Posted October 3, 2015 Share Posted October 3, 2015 You have to restrict the random generated number to total index required in array ( 4 starting at 0 and ending at 3 )$random = mt_rand(0, (count($photo)-1)); Link to comment Share on other sites More sharing options...
Chikwado Posted October 4, 2015 Share Posted October 4, 2015 Do not input double quote inside double quote. Link to comment Share on other sites More sharing options...
dsonesuk Posted October 4, 2015 Share Posted October 4, 2015 Do not input double quote inside double quote. Not only that! you need to concatenate the variable (in this example) to the html string content using {$photo} or .$photo. Unless you escape all the html double quotes them with '' echo "<img src="{$photo}" alt="">"; or echo "<img src="" . $photo . "" alt="">"; OR use single quotes to contain string content (my preferred method) echo '<img src="' . $photo . '" alt="">'; Makes the attribute value surrounding quotes double to match normal html so you don't have mix of attributes using one or the other within a page. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now