Emad doom
Emad doom

Reputation: 87

scan dir with limiting files number?

I have written some code to print files inside folder with a limit and offset (like MySQL's LIMIT).

My code:

/*
files:
.
..
read.txt
*/
$dir = "lab";
$limit = 2;
$file_id = 1;
$start = 1;
$files = array();
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    if($file_id > $start and $file_id >= $limit){
        $files[$file_id] = $filename;
    }
    $file_id++;
}   
print_r($files);
/*
files:
Array ( [2] => .. [3] => read.txt ) 
*/

My folders may contain 1000 or more files and this function will be executed for each visitor.

So I want to do this job without looping, is that possible? If it isn't, is there any way to make this faster?

Upvotes: 0

Views: 5256

Answers (2)

Joe
Joe

Reputation: 15812

http://www.php.net/scandir is probably the best way to avoid looping yourself.

If you'd rather, you can also implement a basic START/LIMIT system like this

$start = 5;
$limit = 20;

$thisFile = 0;

while (false !== ($filename = readdir($dh))) {
    // Check the start
    if ($thisFile < $start)
        continue;
    $thisFile++;

    // Check the end
    if ($thisFile > $limit)
        break;

    // Your other code can go in here
}

Upvotes: 2

zerkms
zerkms

Reputation: 255105

You can retrieve whole list of files within directory without any loops with scandir.

After you've retrieved an array of files you can apply any kind of filtering (using array_filter) and limiting (using array_slice)

Upvotes: 0

Related Questions