Reordering an Array in PHP for an Image Gallery
by admin on Jun.06, 2011, under Uncategorized
Say I have a homepage image rotator (as seen here), and grabbing the images in any logical order (by date, by name) is not an option. Well, its time to make an array and shuffle it!
The following code snippet grabs all the image files within a certain directory, turns them into an array (using the readdir function, which un-modified would order them according to the timestamp on the server), and then randomizes it.
Check it out:
$image_dir = "$_SERVER[DOCUMENT_ROOT]/images/home"; // directory on server
$image_relative_path = '/images/home'; // path to images relative to script
$file_types = array('jpg','jpeg','gif','png');
$image_time = '10000'; // seconds each image will display (10000 = 10 seconds)
if ($handle = opendir($image_dir)) {
$dir_array = array();
$count = 0;
while (false !== ($file = readdir($handle))) {
if($file!="." && $file!=".."){
$dir_array[$count] = $file;
$count = $count + 1;
}
}
// ive got my array, now lets Randomize it!
shuffle($dir_array);
$i = (int)(0);
while ($i < $count){
$image_rotation .= /add html around this: '.$image_relative_path.'/'.$dir_array[$i].' ;
$i = $i + 1;
}
closedir($handle);
}
The code uses a jQuery plugin called innerfade to create a cool UX. Enjoy!