I have a code that lists all of the files and folders in a directory. What I can't figure out is how to exclude certain files based on a list of values in an array. For instance, I have an array like the one below. I want to reference this list and exclude any item that contains one of those substrings:
$hideDir = array('.php', '.html', '.css');
Here's my current loop. Any thoughts on what I'm doing wrong?
echo '<ul>';
foreach($hideDir as $v) {
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if (strpos($entry, $v) > -1) {
//do nothing
}else{
echo '<li>' . "$entry" . '</li>' . "
";
}
}
}
closedir($handle);
}
echo '</ul>';
You're close, but you should drop the whole foreach. Just check while reading the dir, whether the current entry's extension (that can be checked with pathinfo()) is in the array, using in_array():
echo '<ul>';
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
// Get entry info
$entryInfo = pathinfo(__DIR__ . DIRECTORY_SEPARATOR . $entry);
// Is this a "hidden" extension?
if (in_array($entryInfo['extension'], $hideDir)) {
// Skip it!
continue;
}
// Otherwise, just list it
echo '<li>' . "$entry" . '</li>' . "
";
}
}
closedir($handle);
echo '</ul>';
Notice that the extension does not contain the dot in front of it, so it should be:
$hideDir = array('php', 'html', 'css');