I am just learning more about using classes in PHP. I know the code below is crap has I need help. Can someone just let me know if I am going in the right direction?
while($entryName=readdir($myDirectory)) {
$type = array("index.php", "style.css", "sorttable.js", "host-img");
if($entryName != $type[0]){
if($entryName != $type[1]){
if($entryName != $type[2]){
if($entryName != $type[3]){
$dirArray[]=$entryName;
}
}
}
}
}
CodePudding user response:
What you seem to want is a list of all the files in your directory that do not have one of four specific names.
The code that most resembles yours that would do it more efficiently is
$exclude = array("index.php", "style.css", "sorttable.js", "host-img");
$dirArray = [];
while ($entryName = readdir($myDirectory)) {
if (!in_array($entryName, $exclude)) {
$dirArray[] = $entryName;
}
}
Alternately, you can dispense with the loop (as written, will include both files and directories in the directory you supply)
$exclude = array("index.php", "style.css", "sorttable.js", "host-img");
$contents = scandir($myDirectory);
$dirArray = array_diff($contents, $exclude);
CodePudding user response:
You actually want to filter your input:
<?php
$input = [".", "..", "folderA", "folderB", "file1", "file2", "file3"];
$blacklist = [".", "..", "folderA", "file1"];
$output = array_filter($input, function($entry) use ($blacklist) {
return !in_array($entry, $blacklist);
});
print_r($output);
The output is:
Array
(
[3] => folderB
[5] => file2
[6] => file3
)
Such approach allows to implement more complex filter conditions without having to pass over the input data multiple times. For example if you want to add another filter condition based on file name extensions or file creation time, even on file content.