470,810 Members | 964 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,810 developers. It's quick & easy.

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

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
2 1208
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
Thanks for the info.

Dec 21 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

21 posts views Thread by AES/newspost | last post: by
3 posts views Thread by groucho | last post: by
7 posts views Thread by Roshawn Dawson | last post: by
22 posts views Thread by gagan.singh.arora | last post: by
10 posts views Thread by Mike.Duffy | last post: by
reply views Thread by mihailmihai484 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.