Reputation: 519
I'm trying to get the uploaded images from a directory and shuffle their order. I'm able to get the images and display them in order quite easily but can't seem to get them shuffled!
<?php
$imagesDir = 'uploads/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
?>
<div id="images">
<?php
$print_r($images);
$shuffleimages = shuffle($images);
foreach($shuffleimages as $shuffleimage) {
echo '<img src="'.$shuffleimage.'" />';
}
?>
</div>
When I print $images
I get:
Array (
[0] => uploads/image1.jpg
[1] => uploads/image2.jpg
[2] => uploads/image3.jpg
[3] => uploads/image4.jpg
[4] => uploads/image5.jpg
)
I don't know if it's something to do with the glob function or how I'm retrieving the images more generally? I've looked around other questions on SO but can't seem to see what I'm doing differently/wrong!
Upvotes: 2
Views: 557
Reputation: 13544
You also may use sacndir
and use the sorting_order
parameter to shuffle files by sorting them.
Upvotes: 0
Reputation: 7515
You are going one step too far .. There is no need to reassign $images
... Your $shuffleimages
will only return a boolean of true
or false
<?php
shuffle($images); // $images will be shuffled.
foreach($images as $shuffleimage) {
echo '<img src="'.$shuffleimage.'" />';
}
?>
Upvotes: 4