How to ignore a specific file in a directory?

1

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); 
    
asked by anonymous 24.02.2018 / 19:10

1 answer

1

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

Example:

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

If 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, however you use the || sign. This signal in the condition structure equals 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 they exist, you ignore them. 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);
    
24.02.2018 / 19:14