0

I'm using a PHP script which gets data from a text file and displays three random images in a php page. The problem I'm having is that three images don't always show on the page :/ When refreshing the page to see the new random images, sometimes only 1 image will display, sometimes only 2, and then sometimes three. I want three random images to display always. Does anyone have any ideas what I could add to make sure three images always display? :S

php:

 <?php 
 $random = "random.txt";
$fp = file($random);
shuffle($fp);
$keys = array_rand($fp, 3);
for ($i = 0; $i < 3; $i++):
$rl = $fp[$keys[$i]]; 
echo $rl;
endfor;
?>

html:

 <div class="imagecontainer">
 <?php include('rotate.php') ?>
 </div>
4
  • 1
    Is there any logic to when the images get displayed and when not? i.e. are certain images never displayed? Have you looked at the HTML source when one or more of the images aren't displayed to see if anything's wrong there? ps you might find it easier to use foreach() rather than for() in a situation like this. Commented Nov 28, 2011 at 8:39
  • I just want each of the three random images be different - so there are no duplicate random images shown at once. I checked out the html source when only 1/2 images are shown, and it just shows that only one/two images are printed :( Commented Nov 28, 2011 at 8:52
  • 1
    Have you examined the contents of the $fp array? Is it possible that there are blank lines in there? Commented Nov 28, 2011 at 9:26
  • Ahh yes there was a blank line ><;; Thank you, it works fine now! :) Commented Nov 29, 2011 at 19:04

1 Answer 1

3

array_rand() serves the keys (and values) of your file-array but does NOT re-index them zero-based. Let's say your array has 5 elements, 0 to 4. Then getting random keys can result in an array containing (0 => "img0", 2 => "img2", 4 => "img4").

Your loop only cares for the index with number 0 to 2. That's why in some cases you are missing some of your images.

Try using for_each to loop through your $keys-array. This should ignore the index numbers of your array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.