Jump to content

Print directory listing to array


jaaames

Recommended Posts

I'm not sure how complex this is, but I'm relatively new to PHP, so I'll ask anyways.

Let's say I have a directory of text files, each containing information. And I'd like to list them in an array, for later manipulation.

How could I do this? I'm not very knowledgeable when it comes to file I/O. Please help?
Link to comment
https://forums.phpfreaks.com/topic/25651-print-directory-listing-to-array/
Share on other sites

This should do the trick! $dir is the path to the required directory.  At the end, $file_list is an array of all filenames in the directory.

[code]
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if( $file != "." && $file != ".." )
{
$file_list[] = $file;
}
}
closedir($handle);
}
[/code]
NOT asking would be stupid.  ;)

What you need is a 'for loop' (read about them at [url=http://uk.php.net/manual/en/control-structures.for.php]http://uk.php.net/manual/en/control-structures.for.php[/url])

[code]
for( $i=1; $i<=5; $i++ )
{
  echo $file_list[$i] . "\n"    // print filename and a new-line
}
[/code]

Be aware though that arrays are generally 0-indexed, meaning the first filename is at $file_list[0].  In that case change the for loop to

[code]
for ($i=0, $i<=4; $i++ )
[/code]

There are simpler (better?) control structures like 'while' and 'foreach', but for something like this I'd use 'for'
[quote author=brendandonhue link=topic=113297.msg460344#msg460344 date=1162263316]
You could just do $array = glob('*.txt'); to get an array with the names of all the text files. You can use a loop like for() to display only the first 5.
[/quote]
Yeah, probably a better technique.  Head like a sieve me... :D

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.