By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,110 Members | 1,659 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,110 IT Pros & Developers. It's quick & easy.

Need to capture only 5 random urls from a directory of hundreds

P: n/a
This code:

<?
//PHP SCRIPT: getimages.php
Header("content-type: application/x-javascript");

//This function gets the file names of all images in the current
directory
//and ouputs them as a JavaScript array
function returnimages($dirname="images") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image
extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'fadeimages['.$curimage.']=["images/'.$file .'", "", ""]';
echo "\n";
$curimage++;
}
}

closedir($handle);
}
return($files);
}

echo 'var fadeimages=new Array();'; //Define array in JavaScript
echo "\n";

returnimages() //Output the array elements containing the image file
names
?>

captures every file in the images directory into the fadeimages array.
How can I tell php to randomly capture only 5 or so of the images and
store only those in the array? Any help would be greatly appreciated!

Dec 16 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
NC
gu********@gmail.com wrote:

This code captures every file in the images directory into
the fadeimages array. How can I tell php to randomly
capture only 5 or so of the images and store only those
in the array?


Instead of outputting every file name, store file names in an array
(lets say, $files) and then randomly draw five elements from that
array:

$n = count($files) - 1;
for ($i=1; $i <= 5; $i++) {
echo 'fadeimages[', $i, ']=["images/', $files[rand(0, $n)] ,'", "",
""]';
}

For more information on rand(), see the Manual:

http://www.php.net/rand

Cheers,
NC

Dec 16 '05 #2

P: n/a
Thanks for the info.

Dec 21 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.