Reputation: 65
I have this code that I've been using to select one random image. Now I need to select four random images.
I've tried to modify the code and it does work but I can't figure out a way to prevent the same images appearing twice. My knowledge of php is basic at best.
Can anyone shed any light please?
Thanks
my code
<?php
$root = $_SERVER['DOCUMENT_ROOT'];
$path = '/_/images/banners/';
function getImagesFromDir($path) {
$images = array();
if ( $img_dir = @opendir($path) ) {
while ( false !== ($img_file = readdir($img_dir)) ) {
if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) {
$images[] = $img_file;
}
}
closedir($img_dir);
}
return $images;
}
function getRandomFromArray($ar) {
mt_srand( (double)microtime() * 1000000 );
$num = array_rand($ar);
return $ar[$num];
}
$imgList = getImagesFromDir($root . $path);
$imgA = getRandomFromArray($imgList);
$imgB = getRandomFromArray($imgList);
$imgC = getRandomFromArray($imgList);
$imgD = getRandomFromArray($imgList);
?>
<img src="<?php echo $path . $imgA ?>" alt="<?php echo ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgA)) . ' Logo'; ?>">
<img src="<?php echo $path . $imgB ?>" alt="<?php echo ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgB)) . ' Logo'; ?>">
<img src="<?php echo $path . $imgC ?>" alt="<?php echo ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgC)) . ' Logo'; ?>">
<img src="<?php echo $path . $imgD ?>" alt="<?php echo ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgD)) . ' Logo'; ?>">
Upvotes: 1
Views: 217
Reputation: 8654
Use array_rand()
to obtain a list of the desired number of random keys, not just one. The second argument specifies how many keys should be returned:
<?php
$randomKeys = array_rand($imgList, 4);
foreach($randomKeys as $key) {
echo '<img src="' . $path . $imgList[$key] . '" alt="' . ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgList[$key])) . ' Logo">';
}
Upvotes: 1
Reputation: 59701
This should work for you:
Here I just grab all files out of the directory with glob()
. After this I filter the array with array_filter()
and only grab the files which matches to the array: ["gif", "jpg", "png"]
. I do this with a simple in_array()
check where I get the extension of the file with pathinfo()
and take it in lowercase with strtolower()
.
To get now random images I just shuffle()
the array and take X images from the array start with array_silce()
.
At the end I just simple print all images.
<?php
$root = $_SERVER['DOCUMENT_ROOT'];
$path = '/_/images/banners/';
$random = 4;
$images = array_filter(glob($root . $path . "*.*"), function($v){
return in_array(strtolower(pathinfo($v, PATHINFO_EXTENSION)), ["gif", "jpg", "png"]);
});
shuffle($images);
$randomImages = array_slice($images, 0, $random);
foreach($randomImages as $v)
echo "<img src='" . $v . "' alt='" . ucfirst(pathinfo($v, PATHINFO_FILENAME)) . " Logo'>";
?>
Upvotes: 2