Question

I am writing a simple fishing game in PHP. I have a snippet of code that's printing all of the image files in my /img directory, but it's also outputting .DS_Store. I want to exclude that file, maybe using glob(), but I don't know how. I've googled this for hours with no luck.

$files = scandir('img');
if ($files !== false) {
    foreach($files as $f) {
        if ($f == '..' || $f == '.') continue;
            echo '<li class="fish_pic"><img src="img/'.$f.'" alt="'.$f.'" title="" class="fish"></li>'."\n";
    }
}

How can I exclude .DS_Store?

Was it helpful?

Solution 2

$files = scandir('img');
if ($files !== false) {
    foreach($files as $f) {
        if ($f == '..' || $f == '.' || substr($f, -strlen(".DS_Store")) === ".DS_Store") continue;
            echo '<li class="fish_pic"><img src="img/'.$f.'" alt="'.$f.'" title="" class="fish"></li>'."\n";
    }
}

OTHER TIPS

Just add an if rule.

if ($f == '..' || $f == '.' || $f == '.DS_Store') continue;

Alternatively, you could use an array and in_array() method.

$filesToSkip = array('.', '..', '.DS_Store', 'other_file_to_skip');

$files = scandir('img');
if ($files !== false) {
 foreach($files as $f) {
   if (in_array($f, $filesToSkip)) continue;
   echo '<li class="fish_pic"><img src="img/'.$f.'" alt="'.$f.'" title="" class="fish">   </li>'."\n";
 }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top