PHP Option Select Menu Generator Function - Dropdown Menu


/ Published in: PHP
Save to your folder(s)

I wrote this little bit of code myself so if you see where you can improve on it, let me know. This is great for making complex menu's and also for making sure your POST data gets saved and reselected when the screen refreshes. I use it in all my programs now, makes menu generation a snap.

In order to use this you need to make sure you set at minimum
$menu_vars as an array of values and $menu_postvalue as a string to the be the name of the POST field. By default, if no $menu_values is set, $menu_vars will be set both to be the display and value.

Example Usage in the Snippet

I look forward to your feedback.


Copy this code and paste it in your HTML
  1. function menu_generator($menu_vars="",$menu_postvalue="",$menu_values="", $blank=true, $selected="", $class="")
  2. {
  3. if($selected)
  4. {
  5. $selector=$selected;
  6. }
  7. else
  8. {
  9. $selector=$_POST[$menu_postvalue];
  10. }
  11. if(!$menu_values)
  12. {
  13. $menu_values=$menu_vars;
  14. }
  15. else
  16. {
  17. $menu_values=$menu_values;
  18. }
  19. $menu_generate=str_replace(" ", " ", $menu_vars);
  20. $menu_generate2 = str_replace(" ", " ", $menu_values);
  21. echo "<select name=\"$menu_postvalue\" $class >";
  22. if($blank)
  23. {
  24. echo "<option value=\"\"></option>";
  25. }
  26. for($i=0; $i < count($menu_generate); $i++)
  27. {
  28. $value=$menu_generate[$i];
  29. $value2=$menu_generate2[$i];
  30. if($value2 == $selector)
  31. {
  32. echo "<option value=\"$value2\" selected=\"selected\">$value</option>";
  33. }
  34. else
  35. {
  36. echo "<OPTION value=\"$value2\">$value</option>";
  37. }
  38. }
  39. echo "</select>";
  40. }
  41.  
  42. $menu_vars = array("One","Two","Three");
  43. $menu_postvalue = "Numbers";
  44. menu_generator($menu_vars, $menu_postvalue);

URL: http://www.esotech.org

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.