Page 1 of 1
str_repeat trouble
Posted: Sat Mar 12, 2011 5:11 pm
by caruus
I want to generate a html img tag with a src value that points to a random img in a specific directory. This I have done successfully in the random_img.php file. Now I want to have 50 random img displayed on a page without having to write 50 include-lines. This is my code:
Code: Select all
<?php
$get_random_image = include 'include/random_img.php';
echo str_repeat($get_random_image, 50);
?>
It only displays one img and 50 1s (11111111111111111111111111111111111111111111111111)
Help...
Re: str_repeat trouble
Posted: Sun Mar 13, 2011 3:55 am
by cpetercarter
The include() function returns true (1) on success and false (0) plus a warning on failure. So the variable $get_random_image contains the value 1 or 0, not the image tag which you want. You need to restructure your code so that random_image.php contains a function which returns the image tag. Then include random_img.php once, and call the function 50 times using a 'while' loop.
Re: str_repeat trouble
Posted: Sun Mar 13, 2011 12:31 pm
by caruus
cpetercarter wrote:The include() function returns true (1) on success and false (0) plus a warning on failure. So the variable $get_random_image contains the value 1 or 0, not the image tag which you want.
But it does return one random img tag. Why it returns 50 1s I don't understand...?
cpetercarter wrote:You need to restructure your code so that random_image.php contains a function which returns the image tag. Then include random_img.php once, and call the function 50 times using a 'while' loop.
I see a problem here. If I do like this, I will not get 50 random img tags, but call the same function 50 times and get the one random img tag 50 times. Can you see the same?
Re: str_repeat trouble
Posted: Mon Mar 14, 2011 1:54 am
by cpetercarter
Yes, of course it displays one image tag. When you include() random_img.php, the code in the file runs - once. The 50 1's are the result of echoing the value of $get_random_image 50 times.
Running the code in random_image.php once and outputting the result 50 times will produce the same image 50 times, as you say. What you need is to run the code (or the bit of it which produces the image tag) 50 times and output the result each time. This is most conveniently done by wrapping the relevant bit of code in a function and running the function however often you need.