This basic application converts select boxes into PHP arrays and provides the output as a array that can be used (with the function of your choice) to determine which option was selected before the form was posted.
<?php
/*-----------------------------------------------------------------------------------------*/
// http://www.muffinresearch.co.uk/lab/php/
/*-----------------------------------------------------------------------------------------*/
function array2select($arr,$sel = '',$usekey=1,$nullvalue='')
/*-----------------------------------------------------------------------------------------*/
// This function creates select boxes from arrays.
//
// 1. There is an optional parameter to pass in a selected value. If the array value matches the selected
// value this item will be selected by default in the generated select box.
//
// 2. The default behaviour is for the key of the array to be used as the selectbox value
// if this is not required please make $usekey = 0
//
// 3. The last optional argument gives you control over a string that you would like the value to be an empty string for.
// The obvious example would be the first option if you use something like "Please Select"
//
// Check out http://www.muffinresearch.co.uk/lab/php/select2array/ for a means to convert select-box options
// To a PHP array. Saves ages if you already have the options and you need to make them into arrays.
/*-----------------------------------------------------------------------------------------*/
{
while (list( $key, $val ) = each($arr))
{
if($sel && $usekey && ($key == $sel || is_array($sel) && in_array($key,$sel)))
{
$select_v=" selected='selected'";
}
else if ($sel && !$usekey && ($val == $sel || is_array($sel) && in_array($val,$sel)))
{
$select_v=" selected='selected'";
}
else
{
$select_v='';
}
if($nullvalue != '')
{
if ($key == $nullvalue)
{
$key = '';
}
}
if ($usekey == 1)
{
echo "<option value=\"$key\"$select_v>$val</option>\n";
}
else
{
if(($nullvalue != '') && ($key == ''))
{
echo "<option value=\"$key\"$select_v>$val</option>\n";
}
else
{
echo "<option$select_v>$val</option>\n";
}
}
}
}
?>