Hot Dog
Hot Dog

Reputation: 35

PHP: How to display several, random images with 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?

Upvotes: 0

Views: 1151

Answers (3)

Reto
Reto

Reputation: 1343

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

Upvotes: 2

J A
J A

Reputation: 1766

$randomImageIndexes = array_rand($images, 5);

foreach ($randomImageIndexes as $imageIndex){

   echo $images[$imageIndex];

}

Upvotes: 1

Jules Lamur
Jules Lamur

Reputation: 2368

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

Upvotes: 0

Related Questions