I would like to know if it's possible with PHP to sort out a list of .txt files on a hardrive, in to an Alphabetical Index Page, with the first letter of the .txt file example: "A", into a seperate page with all the files starting with the letter "A", and so on. What function would be at use here?
Altough it's working somehow, your code has some flaws. For example, you don't actually need the count() at all (it gets the size of an array and you use it on string -- the filename -- which will always return 1), and you have to do some more thinking when outputting the filenames.
Please see my version of the code and try to see what I have changed. Hopefully it will get you started!
PHP Code:
<?php
$dir = ".";
$filenames = array();
if ($handle = opendir($dir)) {
/* read every entry from the given directory */
while (false !== ($file = readdir($handle))) {
/* check if we got a valid entry (file or dirname) */
if ($file != "." && $file != "..") {
/* append current filename to array */
$filenames[]=$file;
}
}
closedir($handle);
/* show what we got */
$numfiles = count($filenames);
echo "total of $numfiles files.<br>\n";
Oh, one more thing: check the functions is_dir() and is_file() for getting just the filenames and no directorynames. Or, with these you can make the code 'recursive' so that it will get all the filenames from all the directories below the given one -- that's your next challenge
Thx, mate this is exactly what I wanted for the array. I'll look at those functions as well. The only thing I'm interested now is to declare the arrays with the individual starting letters into a seperate page.
Here's a little addition to the previous code -- it will create a new array with alphabet keys and adds each filename in it's corresponding subarray in the main array.
PHP Code:
/* sort filenames alphabetically in ascending order */
/* SORT_NUMERIC seems to ignore character case */
sort($filenames, SORT_NUMERIC);
$array = array();
/* add each filename to the array by it's first letter */
foreach($filenames as $filename) {
$firstletter = strtolower(substr($filename, 0, 1));
$array[$firstletter][] = $filename;
}
/* sort the new array by it's keys (alphabets) */
ksort($array);
/* show the results */
echo "<pre>";
print_r($array);
echo "</pre>";