Jump to content

Randomise file list


garethhall

Recommended Posts

Hello,

 

Can someone help me out here please. I have the code below that looks for all the jpg files in the folder and works great but I need the files that are returned to be in a random order. How can I do this?

 

Here is my code

<?php
	$headerImages = "sites/default/files/images/header_images/";
	$allowed_types = array('png','jpg','jpeg');
	// create a handler for the directory
	$headerImageContainer = opendir($headerImages);

	$filecount = count(glob("" . $headerImages . "*.jpg"));
	$filecount += count(glob("" . $headerImages . "*.jpeg"));

	// keep going until all files in directory have been read
	while ($file = readdir($headerImageContainer)) {
		$ext = pathinfo($file, PATHINFO_EXTENSION);//get extention of file
		if(in_array(strtolower($ext),$allowed_types)){
		$i++;
		echo "{ src: '/sites/default/files/images/header_images/".$file."' }".($i!=$filecount?',':'');
		}
	}
	// tidy up: close the handler
	closedir($headerImageContainer);
	?>
	]);
});

 

Link to comment
https://forums.phpfreaks.com/topic/198965-randomise-file-list/
Share on other sites

try this

while ($file = readdir($headerImageContainer)) {
$ext = pathinfo($file, PATHINFO_EXTENSION);//get extention of file
if(in_array(strtolower($ext),$allowed_types)){
$i++;
$files[]=array("src"=>"/sites/default/files/images/header_images/".($i=$filecount?)?',':""); 
//echo "{ src: '/sites/default/files/images/header_images/".$file."' }".($i!=$filecount?',':'');
}
}
$files=shuffle($files);
// then you can do whatever you want with the array 

Link to comment
https://forums.phpfreaks.com/topic/198965-randomise-file-list/#findComment-1044379
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.