Tiffany B. Brown

Turn text files into pull down menus

UPDATE: This could also be done with the foreach() construct, but here — on my set-up at least — the for loop is a teensy bit faster.

I developed this PHP function for a project I’m working on. I’m posting it here in case I need it again, or in case you find it handy.


#Input text files must contain one item per line

function print_menu($txtfile_or_files){

	$args = func_get_args(); 

	$num_args = func_num_args();

	$input = array();

	

	for($i = 0; $i < $num_args; $i++){

		// get contents of each text file specified 

		$lines = file($args[$i]); 

		

		// get each line from each file an add to array

		for($j = 0; $j < count($lines); $j++){

			array_push($input,$lines[$j]);

		}

	}

	// sort alphabetically

	sort($input,SORT_STRING);		

	

	for($i = 0; $i < count($input); $i++){	

		$value = str_replace(' ','_',strtolower(trim($input[$i])));

		echo '<option value="'.$value.'">'.trim($input[$i])."</option>\n";

	} 

}

Configuration and use

The variable $txtfile_or_files should be a comma-separated list of paths to plain text files. This function accepts multiple arguments, in case you want to string multiple files into one menu.

Each text file should contain one item per line. For example:


Red

Blue

Orange

Green

Add another line or two of code if you need to indicate whether the form field value has already been selected.

4 Responses to “Turn text files into pull down menus”

  1. [...] Brown shares a quick function she whipped up to create dropdown menus from the contents of a newline separated text file (or [...]

  2. [...] Turn text files into pull down menus • Tiffany B. Brown (tags: php code webdev useful programming) [...]

  3. J. Graham says:

    Awesome! My students will love it! Thanks, jg

  4. J. Graham says:

    Awesome! My students will love it! Thanks, jg