str_repeat trouble

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
caruus
Forum Newbie
Posts: 2
Joined: Sat Mar 12, 2011 4:52 pm

str_repeat trouble

Post 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...
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: str_repeat trouble

Post 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.
caruus
Forum Newbie
Posts: 2
Joined: Sat Mar 12, 2011 4:52 pm

Re: str_repeat trouble

Post 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?
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: str_repeat trouble

Post 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.
Post Reply