随机选择一个文件

Im writing a script to send a random image by email to myself daily, what i want to do is set a variable $image to equal a 'random' image in a directory called /images.

It dosnt matter which the image is just (ie. it dosnt need to be truly random it could be done on date, image size, alphabetical name ect.)

The images are a mixture of .jpg, .jpeg, .png, .gif.

Whats the best way to assign a random image to the $image vairable ?

 $images = array('image1.png', 'image2.png', 'image3.jpg');

 $selectedimage = rand(0,count($images));

 $image = $images[$selectedimage];

Something like this might work..

$files = scandir('/images');
$images = array();
foreach ($files as $file) {
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    switch($ext) {
    case 'jpg':
    case 'png':
    case 'gif':
        $images[] = $file;
        break;
    }
}

$image = $images[array_rand($images)];

If I were doing it, i'd do it more like a deck of card, where every card in the deck would be used once, then start over again with the full deck. Simply pulling a random image would allow the same image to be returned back to back.

Starting with a full deck of cards, pick any one of 52. swap card 52 with the one which has been drawn and return the drawn card to position 52 (the bottom of the deck).

Next draw a card 1-51. Swap the drawn card with card 51.

draw a card 1-50 and swap the drawn card with card 50.

repeat till there is only 1 card, then when card 1 gets swapped with card 1, reset the pick count to 52.

Start over again, pick card 1-52, and swap the card with #52, then 1-51, 1-50...