Search code examples
phplistdir

Listing certain extensions in PHP Dir List


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


Solution

  • 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.