tags:

views:

43

answers:

2

Thanks in advance to anyone who takes time to respond. I truly appreciate this site! I've got a function that loads all images it finds in a given directory (see below). The problem I'm trying to resolve is that the images are loaded in a random order.

I'd like the images to be loaded by alpha order based on their filename (widget-1.jpg would load before widget-2.jpg for example).

Function is below...

function get_images()
{
global $options;
 foreach ($options as $value) {
 if (get_settings( $value['id'] ) === FALSE) { $$value['id'] = $value['std']; } else { $$value['id'] = get_settings( $value['id'] ); }
}
if($my_custom_images !== "")
{
echo $my_custom_images;
}
else
{
$dir = 'wp-content/uploads/';
$url = get_bloginfo('url').'/wp-content/uploads/';
$imgs = array();
 if ($dh = opendir($dir)) 
 {
 while (($file = readdir($dh)) !== false) 
  {
  if (!is_dir($file) && preg_match("/\.(bmp|jpeg|gif|png|jpg|)$/i", $file)) 
   {
    array_push($imgs, $file);
   }
  }
  closedir($dh);
 } else {
  die('cannot open ' . $dir);
 }

 foreach ($imgs as $idx=>$img) 
 {
  $class = ($idx == count($imgs) - 1 ? ' class="last"' : '');
  echo '<img src="' . $url . $img . '" alt="' .$img . '"' . $class . ' />';
 }
 }
 }
+2  A: 

Use sort() on $imgs after you have filled it from the directory

Yacoby
Works perfectly Yacoby. Thanks for the help!
Scott B
A: 

They're probably appearing in directory order, sort-of the order in which they were created. Edit: One solution is popen ("ls") and filter the filenames. I see, php doesn't have such a call.

Anyway, I agree with the first answer: sorting the list after it is built is the most general and portable solution.

wallyk