ZADorkMan
ZADorkMan

Reputation: 431

Fetch images randomly from directory?

I am no too proficient in PHP yet and I have this code which works so far.

<?php 
$id = JRequest::getInt('id');
$dirname = "media/k2/galleries/{$id}/";
$images = glob($dirname."*.jpg");
$rand = array_rand($dirname);
?>
<?php foreach($images as $image): ?>

<li><span class="shadowborder"><img src="<?php echo $image ?>" /></span>    </li>
 <?php endforeach; ?>

I have tried to add an array, I know $images and $image should be swapped out but as you can see but I cannot get it to gel, what am I missing? Thanks!

Upvotes: 0

Views: 79

Answers (2)

apokryfos
apokryfos

Reputation: 40653

You can use shuffle for this:

$id = JRequest::getInt('id');
$dirname = "media/k2/galleries/{$id}/";
$images = glob($dirname."*.jpg");
shuffle($images);
?>
<?php foreach($images as $image): ?>

<li><span class="shadowborder"><img src="<?php echo $image ?>" /></span>    </li>
 <?php endforeach; ?>

Upvotes: 1

Zac Webb
Zac Webb

Reputation: 663

You can use the 'Glob' function in partnership with array_rand() to achieve this:

<img src="
    <?php
        $id = JRequest::getInt('id');
        $imagesDir = 'media/k2/galleries/{$id}/';
        $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
        $randomImage = $images[array_rand($images)];
        echo $randomImage;
    ?>
">

You can modify which file-types to 'allow' via changing (adding/removing) this part:
'*.{jpg,jpeg,png,gif}


Feel free to ask any further questions.

Upvotes: 1

Related Questions