1

I have the following section of code. Is there anyway that I can use the php rand() function to randomly display items within the foreach?. I have tried google but I am getting confused how to implement it into this situation.

<?php
$dir = 'catalog/view/theme/default/gallery/';?>
<div id="Box">
<div id="slideShow">
<ul>
<?php foreach(glob($dir.'*.jpg') as $file) : ?>
<li><img width="370" height="480" alt="" src="<?=$file?>"/></li>
<?php endforeach; ?>
</ul>
</div>
</div>
1
  • You don't want the files in the order that the glob() returns them to you in? Commented Jul 14, 2011 at 4:27

3 Answers 3

4

Assuming you want to display all of the images but in a random order, you could try something like this:

<?php
    $files = glob($dir . "*.jpg");
    shuffle($files);
    foreach($files as $file):
?>
<li><img width="370" height="480" alt="" src="<?= $file ?>" /></li>
<?php
    endforeach;
?>
Sign up to request clarification or add additional context in comments.

Comments

1

I have used rand() in my SELECT query before using foreach like order by rand() it too worked.

Comments

0

You could read the files into an array and use array_rand

http://php.net/manual/en/function.array-rand.php

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.