0

Have the following to provide a dir list in an array

for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != ".") { // don't list hidden files
 echo "<option value=\"".$dirArray[$index]."\">".$dirArray[$index]."</option>";
 }

Is there any way i can modify the above code so that only .JPG and .PNG are displayed?

Thanks!

CP

Chris P
  • 51
  • 2
  • 6
  • possible duplicate of [PHP list of specific files in a directory](http://stackoverflow.com/questions/3062154/php-list-of-specific-files-in-a-directory) – Rene Pot Jul 11 '13 at 15:25
  • `"$dirArray[$index]"` cargo cult programming detected... Perhaps you want http://php.net/pathinfo to extract file extensions from filenames. – Marc B Jul 11 '13 at 15:26
  • There are some similarities but I can't see how without rewriting everything that I would be able to get these types listed. – Chris P Jul 11 '13 at 15:30

3 Answers3

2
foreach($dirArray[$index] as $k => $v) {
     if(in_array(pathinfo($v, PATHINFO_EXTENSION), array('jpg', 'png', 'jpeg')) {
         echo '<option value="'.$v.'">'.$v.'</option>';
     }
}

I am assuming some things about your array of files. Also is there a reason you're not using the readdir() function?

Fabor
  • 567
  • 9
  • 21
1

You can use regular expression to match if file name ends with .jpg or .png

for($index=0; $index < $indexCount; $index++) 
{
    if(preg_match("/^.*\.(jpg|png)$/i", $dirArray[$index]) == 1) 
    {
      echo "<option value=\"".$dirArray[$index]."\">".$dirArray[$index]."</option>";
    }
}

/i at the end of regular expression is case insensitive flag.

Harshveer Singh
  • 4,037
  • 7
  • 37
  • 45
  • Hey Harshveer, thanks for your help. Have had a go at doing this but it still displays the other types. What am I doing wrong? – Chris P Jul 11 '13 at 15:30
0
for($index=0; $index < $indexCount; $index++) {
        if (substr($dirArray[$index], 0, 1) != "." 
            && strtolower(substr($dirArray[$index], -3)) == 'png' 
            && strtolower(substr($dirArray[$index], -3)) == 'jpg')
            echo '<option value="'.$dirArray[$index].'">'.$dirArray[$index].'</option>';
 }

This should work, but there are more elegant solutions to this, like using DirectoryIterator (see here):

foreach (new DirectoryIterator('your_directory') as $fileInfo) {
    if($fileInfo->isDot() 
        || !in_array($fileInfo->getExtension(), array('png', 'jpg'))) 
        continue;
    echo sprintf('<option value="%s">%s</option>', 
        $fileInfo->getFilename(), 
        $fileInfo->getFilename());
}

Code not tested, you might need to fiddle a bit with it.

RedPoppy
  • 573
  • 4
  • 11