How to ignore a specific file in directory?

Asked

Viewed 93 times

0

The code below counts all files in my directory, but I want to ignore the file index.php

$i=0;
foreach (glob ("*.*") as $file){
$a[$i] = $file;
$i++;
}
echo count($a); 

1 answer

1


Use the one if or unset to ignore or remove, respectively, the index array.

Example:

foreach (glob ("*.*") as $file){
    if ($file != "index.php") {
        $a[] = $file;
    }
}
echo count($a);

In case you want to ignore all index.php:

foreach (glob ("*.*") as $file){
    if (!preg_match("/index\.php$/", $file)) {
        $a[] = $file;
    }
}
echo count($a);

Or just remove it from the array $a.

foreach (glob ("*.*") as $file){
    $a[] = $file;
}

/* Verifica se o arquivo existe no array */
if (isset($a["index.php"])) {

    /* Caso exista, remove ele. */
    unset($a["index.php"]);
}
echo count($a);

To ignore two or more files, you use the same way as the first example, but you use the sign ||. This sign in the condition structure is equivalent to the OU. Example:

foreach (glob ("*.*") as $file){
    /* Se o nome do arquivo for diferente de "index" OU diferente de "config.php , armazena variável $a */
    if ($file != "index.php" || $file != "config.php") {
        $a[] = $file;
    }
}
echo count($a);

But you can also use an array with the names you want to ignore and then use in_array to check if these values exist, if any, you ignore. Example:

$filesIgnore = ['index.php', 'config.php'];

foreach (glob ("*.*") as $file){
    /* Se o nome do arquivo não existe na variável $filesIgnora, adiciona ele na variável $a */
    if (!in_array($file, $filesIgnore)) {
        $a[] = $file;
    }
}
echo count($a);
  • First solved example, wonder. Now painted another doubt how to ignore 2 files? index.php and config.php

  • @Rose edited my reply. I added a few more examples.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.