need script made very easy php

Discussion in 'PHP' started by stickycarrots, Jan 14, 2008.

  1. #1
    i need a script made that will pick a random image from a folder or a list

    know what i mean
     
    stickycarrots, Jan 14, 2008 IP
  2. nals

    nals Peon

    Messages:
    168
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    nals, Jan 14, 2008 IP
  3. rkquest

    rkquest Well-Known Member

    Messages:
    828
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    140
    #3
    Try this..
    
    <?php
    
    $files = scandir('./images/');
    $filter = array('', '.', '..');
    $file = '';
    while (in_array($file, $filter)) {
    	$file = $files[array_rand($files, 1)];
    }
    
    echo $file; // do whatever you want with this result.
    
    ?>
    
    PHP:
     
    rkquest, Jan 14, 2008 IP
  4. nals

    nals Peon

    Messages:
    168
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    nals, Jan 15, 2008 IP
  5. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Wouldn't you have an infinite loop if the folder happens to be empty?
     
    SmallPotatoes, Jan 15, 2008 IP
  6. rkquest

    rkquest Well-Known Member

    Messages:
    828
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    140
    #6
    I don't think there will be an infinite loop because because the resulting array of scandir will always have two entries - . and .. even if there are no files inside the directory. But that's only based on my observation..

    Just to be safe.. here's a modified version.

    
    <?php
    
    $files = scandir('./images/');
    $filter = array('', '.', '..');
    $file = '';
    if (count($files)>2) {
    	while (in_array($file, $filter)) {
    	    $file = $files[array_rand($files, 1)];
    	}
    }
    
    echo $file; // do whatever you want with this result.
    
    ?>
    
    PHP:
     
    rkquest, Jan 15, 2008 IP
  7. stickycarrots

    stickycarrots Peon

    Messages:
    4,513
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    0
    #7
    thanks for the code it works great
     
    stickycarrots, Jan 15, 2008 IP
  8. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #8
    How would it break out of the loop? Every time through, $file would be '', '.', or '..'.

    But yeah, the fixed version doesn't have this problem.
     
    SmallPotatoes, Jan 15, 2008 IP