3

help me to get files from a folder in array. I am trying to get all jpg file name in array from a folder images. and after that use rand to change css background Randomly.

JPG files from a folder in arry;

$images=array("image1.jpg", "image2.jpg");

then use the rand to load images randomly

echo '<style>body{background:url('.$images[array_rand($images)].')no-repeat;';
5
  • Sooo... What's the question? Do you have what you've tried that's inadequate? Commented Aug 26, 2012 at 14:53
  • I dont know how to get files from a folder in array Commented Aug 26, 2012 at 14:54
  • Manual is your friend - find function written by williamcomartin at gmail dot com Commented Aug 26, 2012 at 14:55
  • 4
    glob: echo '<style>body{background:url('.array_rand(glob("images/*.jpg")).')no-repeat;'; Commented Aug 26, 2012 at 14:57
  • @AaronW. - I'm guessing that would probably make a good answer, although there are other ways too. Commented Aug 26, 2012 at 14:58

2 Answers 2

4

Pass a directory to scandir to get an array of all files in that directory. Maybe use array_filter then to filter out any non-images by file extension.

    $files = scandir( '/image/path' );

    function images_only( $file )
    {
      return preg_match( '/\.(gif|jpg|png)$/i', $file );
    }

    $files = array_filter( $files, 'images_only' );

$files should now contain only the images from the image path.

Sign up to request clarification or add additional context in comments.

Comments

1

glob it

edited with array_rand fix

$images = glob("images/*.jpg");
// may want to verify that the $images array has elements before echoing
echo '<style>body{background:url('.$images[array_rand($images)].') no-repeat;';

2 Comments

Is the path correct? Try debugging to make sure it's populating correctly
array_rand() returns a random key only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.