PHP:如何用array_rand显示几个随机图像?

I'm using this script to display one random image from a folder with subfolders:

<?php
$imagesDir = glob('folders/pics/*', GLOB_ONLYDIR);
$randomfolder = $imagesDir[array_rand($imagesDir)];
$images = glob($randomfolder . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
echo '<img src="'.$randomImage.'" class="image">'; 
?>

Everything works fine! But for now I want to show 5 images at the same time (for a caroussel-slider). I used the following code

$randomImage = $images[array_rand($images, 5)];

but it shows me this warning:

Warning: Illegal offset type […]

What am I doing wrong?

You are using array_rand() function wrong. It will return an array of keys, not a single number. What you could do is:

$randomImageKeys = array_rand($images, 5);
for ($randomImageKeys as $key) {
   echo '<img src="'.$images[$key].' class="image">';
}

But like this you risk an E_WARNING if your $images array contains less than 5 images - to avoid this, you could use the following:

$max = (count($images) < 5) ? count($images) : 5;
$randomImageKeys = array_rand($images, $max);
for ($randomImageKeys as $key) {
   echo '<img src="'.$images[$key].' class="image">';
}
$randomImageIndexes = array_rand($images, 5);

foreach ($randomImageIndexes as $imageIndex){

   echo $images[$imageIndex];

}

Since array_rand($array, $n) returns an array if $n > 1 (c.f. php.net documentation : array_rand), you have to iterate through the result to make your script work.

It should works fine this way :

<?php
$imagesDir = glob('folders/pics/*', GLOB_ONLYDIR);
$randomfolder = $imagesDir[array_rand($imagesDir)];
$images = glob($randomfolder . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
foreach(array_rand($images) as $imageIndex)
    echo '<img src="'.$images[$imageIndex].'" class="image">';