Reputation: 9731
I'm looking for the best way to iterate through a folder and put all the file names inside it into an array and in another one the count of the files.
I have found glob()
as a good solution, but also a lot of alternatives for it on php.net. I'm not sure which I should use, so I'm asking here. If you're wondering for what I want to use it, it's to get all the .sql
files inside a backup
folder and display them as <li>thesqlfile.sql</li>
and have a count of all of them too.
So I thought of having two arrays, one with their names, and one with the count of all of them. So in this case which method would be best fit to iterate ?
Method I:
<?php
$files = array();
foreach (glob("backup/*.txt") as $filename) {
$files[]= $filename;
}
$count = sizeof($files);
?>
Method II:
function getfoldercontents($dir, $file_display = array(), $exclusions = array()) {
if(!file_exists($dir)){
return FALSE;
}
$dir_contents = scandir($dir);
$contents = array();
foreach ($dir_contents as $file){
$file_parts = explode('.', $file);
$file_type = strtolower(end($file_parts));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) && !in_array($file, $exclusions)) {
$contents[] = $dir. '/'. $file;
}
}
return $contents;
}
Upvotes: 0
Views: 710
Reputation: 4366
I would say the second is probably better in terms of file-control (through $file_display and $file_exclude), but maybe you should add a check to ensure the current file is not a directory named something.typeyouwishtodisplay
Upvotes: 0
Reputation: 270785
Since glob()
already returns an array, you don't need to iterate over it to append to an array at all. Your first method is a little over-complicated. This accomplishes the same thing:
// Just assign the array output of glob() to a variable
$files = glob("backup/*.txt");
$num_files = count($files);
Upvotes: 3