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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • guttyguppy@gmail.com

    #1

    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($d irname="images" ) {
    $pattern="(\.jp g$)|(\.png$)|(\ .jpeg$)|(\.gif$ )"; //valid image
    extensions
    $files = array();
    $curimage=0;
    if($handle = opendir($dirnam e)) {
    while(false !== ($file = readdir($handle ))){
    if(eregi($patte rn, $file)){ //if this file is a valid image
    //Output it as a JavaScript array element
    echo 'fadeimages['.$curimage.']=["images/'.$file .'", "", ""]';
    echo "\n";
    $curimage++;
    }
    }

    closedir($handl e);
    }
    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!

  • NC

    #2
    Re: Need to capture only 5 random urls from a directory of hundreds

    guttyguppy@gmai l.com wrote:[color=blue]
    >
    > 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?[/color]

    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:



    Cheers,
    NC

    Comment

    • guttyguppy@gmail.com

      #3
      Re: Need to capture only 5 random urls from a directory of hundreds

      Thanks for the info.

      Comment

      Working...