Search code examples
phpif-statementforeachcontinuescandir

PHP IS_DIR Condition Not Working In Loop With Continue


I know this is a dummy question.
But I have banging my head more than an hour to make it works.

$path = '/dir/path';
$files = scandir($path);
foreach ($files as $file) {
    if (($file === '.' || $file === '..') || (is_dir($file))) continue;
    if (empty($file)) {
        echo $file.'<br>';
    }
}

Suppose I just want to show empty files within a directory than also content subdirectories.

How to make the is_dir condition works with continue statement?

Thanks in advance.


Solution

  • This little typo remind me to start printing or echoing when a problem begin to show up. By that I can find the solution faster.

    The typo is_dir need full path to be executed, so the right code is is_dir($path.'/'.$file).

    $path = '/dir/path';
    $files = scandir($path);
    foreach ($files as $file) {
        if (($file === '.' || $file === '..') || is_dir($path.'/'.$file)) continue;
        if (empty($file)) {
            echo $file.'<br>';
        }
    }