简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM