Moozoo
Moozoo

Reputation: 497

PHP random image number not consistant

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>

Upvotes: 0

Views: 170

Answers (1)

TRD
TRD

Reputation: 1027

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.

Upvotes: 3

Related Questions