Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Alphabetize files from a folder in a select box

Status
Not open for further replies.
Aug 23, 2004
174
US
Is it possible to alphabetize files from a folder in a select box? I was told it is possible with just HTML but after a few hours of searching i'm coming up empty.
 
Maybe a little PHP might help...

Code:
<?php
//deinf the array
$filelist = array();

//check to see if the folder exists
if ($handle = opendir('/usr/bin')) {
	$i=0;
//loop through the folder and store in the array
	while (false !== ($file = readdir($handle))) {
		$filelist[$i] = $file;
		$i++;
	}
	closedir($handle);
}

//sort the array alphabetically
asort($filelist);

//create the select box
echo "<select multiple=yes size=10>";

//loop through the array and add the options
	foreach ($filelist as $k=>$v){
	echo "<option value='$k'>$v</option>";
	}
echo "</select>";
?>

Mark
 
i would not rely on the the numeric key as the identifier or the option items. there is a chance that the directory might change in the meantime.

i'd also add some validation to mark's script

Code:
while (false !== ($file = readdir($handle))) {
        if (is_file($file)){
          $filelist[] = $file;
        }
}

if you do want directories as well, then check instead for the dot and doubledot. but you'd be better off using glob() in that case. or even ls via the backticks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top