user1289939
user1289939

Reputation:

Php get jpg file from a folder as array

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;';

Upvotes: 3

Views: 2582

Answers (2)

Poe
Poe

Reputation: 3010

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.

Upvotes: 4

Aaron W.
Aaron W.

Reputation: 9299

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;';

Upvotes: 1

Related Questions