在PHP目录列表中列出某些扩展

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

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.

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.

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?