1

I have this part of script that echos the folders in "albums" folder and arrange them by the alphabet, but for some reason it also includes an empty folder.

$directory = opendir("albums/");
$items = array();  
while($items[] = readdir($directory))
    sort($items);
closedir($directory);
foreach ($items as $item)
{  
    if(($item != ".") && ($item != "..")){  
        $files[] = $item;
    }
}

What should I do? I think the if(($item != ".") && ($item != "..")) is part of my problem but I can't figure how to handle it.

JJJ
  • 32,902
  • 20
  • 89
  • 102
Elad
  • 75
  • 2
  • 10

4 Answers4

2

The problem is with this line:

while($items[] = readdir($directory))

readdir returns false if no entries are left. That is why you have an extra item in $items

EDIT

while($item = readdir($directory))
{
  $items[] = $item;
  sort($items);
}
Rolando Cruz
  • 2,834
  • 1
  • 16
  • 24
1

. is the current directory and .. is the parent directory. It's normal that readdir() returns these.

BTW you could simplify your code by using the glob() function:

$files = glob("albums/*");
// that's all

glob("albums/*") will return all entries in the albums directory, sorted alphabetically, and without the dot and dotdot entries.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
  • and it will arrange it by the alphabet?? – Elad Sep 11 '11 at 13:33
  • but whem i use it like this - it returns albums/aalbums/balbums/calbums/dalbums/e (there are folders named a,b,c,d,e) and i need it return only a/b/c/d/e.. – Elad Sep 11 '11 at 13:44
0

Try this, as it's in sorted order, just array_shift() twice will do this work. But personally I think it's a kinda hacking...

Dewsworld
  • 13,367
  • 23
  • 68
  • 104
0
<?php
$files = array();

foreach (glob('album/*') as $file) {
    if (!is_dir($file)) {
        $files[] = basename($file);
    }
}

sort($files);

You can modify 'album/*' to suit your needs (ex. 'album/*.mp3'). Note that this method is not recursive, so if you need to process subdirectories within the album/ directory, you'll want to modify the code to account for this.

FtDRbwLXw6
  • 27,774
  • 13
  • 70
  • 107