Rich
Rich

Reputation: 6561

iterate through directory, sort and display items in alphabetical order

I'm using the FilesystemIterator to iterate through a directory called photos then create a hyperlink to each photo like this:

$fileSystemIterator = new FilesystemIterator('photos');
foreach ($fileSystemIterator as $fileinfo) {
  echo "<span class='photos_hyperlink'><a href='displayPicture.php?img=$fileSystemIterator' target='_blank'>";
  echo $fileSystemIterator . "</a></span><br><br>";
}

This works, but items aren't in alphabetical order so to alphabetize them I'm trying to store them in an array, sort, then display. I'm missing something because nothing is being printed to the screen. Could anyone offer some advice on what I'm missing?

$photosArray = array();
$fileSystemIterator = new FilesystemIterator('photos');
foreach ($fileSystemIterator as $fileinfo) {
    $photosArray[$fileinfo->getFilename()];
}

sort($photosArray);

foreach ($photosArray as $val) {
    echo "<span class='photos_hyperlink'><a href='displayPicture.php?img=$val' target='_blank'>";
    echo $val. "</a></span><br><br>";
}

Upvotes: 0

Views: 109

Answers (3)

dazed-and-confused
dazed-and-confused

Reputation: 1333

You need to change your foreach loop from:

foreach ($fileSystemIterator as $fileinfo) {
    $photosArray[$fileinfo->getFilename()];
}

To:

foreach ($fileSystemIterator as $fileinfo) {
    $photosArray[] = $fileinfo->getFilename();
}

Upvotes: 2

the91end
the91end

Reputation: 101

In this line, you are "assigning" the filename into the key of the array

$photosArray[$fileinfo->getFilename()];

Try change it to

$photosArray[] = $fileinfo->getFilename();

Upvotes: 1

pavel
pavel

Reputation: 27082

You store filenames in array keys, not values.

$photosArray[] = $fileinfo->getFilename();

Upvotes: 1

Related Questions