0

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?

3 Answers 3

2

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">';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. Your solution works fine! And to all the other helping hands: Thank you :-)
1
$randomImageIndexes = array_rand($images, 5);

foreach ($randomImageIndexes as $imageIndex){

   echo $images[$imageIndex];

}

Comments

0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.