Dynamic creation of HTML select menu from PHP arrays

Written by Ian on 26/08/08


Assume you have a single PHP array called my_array(). Then you want to have a pulldown select menu where users can choose one of the elements from that array and assign it to a variable...


Then when someone clicks 'submit' you go to another HTML page where you want to use that variable.


And in addition you want to remember the variable choices for next time you return to this page! Here is how you do it.



1. Start with a blank php file. Begin it, as usual with the start and end identifiers to signify a PHP page.



2. Right after the php start identifier, place a:


start_session()



3. Next create a function that can be called to make a select menu and store it as a string:


//----
function makeSelectMenu($menuName, $options, $chosen) {
$list = '';
foreach ($options as $option) {
$selected = ($chosen == $option) ? ' selected="selected"' : '';
$list .=" < option value=\"$option\"$selected > $option < /option > \\\\n"; ;
}
return "\\\\n < select name=\"$menuName\" id=\"$menuName\" >\\\\n$list </select >\\\\n";
}
//---


Place this function somewhere near the top of your PHP page.



4. Next we are going to create an array, and fill it with some values.


$days=array();
for ($i=1;$i<=366;$i++)
$days[]=strval($i);


5. Now we will do something interesting - we will add some code that can store and remember a variable called $selectDay, and pass it to subsequent pages:

if (isSet($_POST['selectDay']))
$_SESSION['selectDay'] = $_POST['selectDay'];
if (isSet($_SESSION['selectDay']))
$choice = $_SESSION['selectDay'];
else
$choice = '';



6. Right after that, pass the $choice variable to the function we had above, along with the array of values we had created, and the name of the variable we want to have set once the selection has been made:


$dayMenu = makeSelectMenu('selectDay', $days, $choice);



7. So far this page hasn't actually displayed any HTML... So now we can do this all in one form:


echo "< form name=\"input\" action=\"nextpage.php\" target=\"_new\" method=\"post\" >";
echo "day: ".$dayMenu;
echo "\  \<input type =\"submit\" value =\"Submit\">";
echo "< /form >";



8. So all this should work nicely. But notice that the HTML form above will, when the user makes a choice and clicks 'Submit' load another PHP page called nextpage.php. Inside nextpage, if we want to use the variables we have just passed over we need to do this:


if (isSet($_POST['SelectDay']))
$day = $_POST['SelectDay'];
else
$day = 'Not selected';


And then we can use the variable $day in that page to do whatever we want.


I hope this is useful! If you try this in your page, and find it works for you, please link to us or acknowledge us somewhere on your site!!