etm124
etm124

Reputation: 2140

Pre-filling select tags from array

I've got this array:

$profession_type = array(
   'Professional Engineers',
   'Accountants',
   'Insurance Professionals',
   'Attorneys',
   'Certified Hazardous Materials Managers',
   'Safety Professional',
   'Industrial Hygienists',
   'IT Professionals',
   'Human Resource'
);

I am display the contents of the array as the options for the select tag:

                        <select name="profession_type[]">
                            <option value=""></option>
EOL;
    foreach ($profession_type as $p){
        print "<option value='" . $p . "'>" . $p . "</option>";
    }
print <<<EOL
                        </select>

I've never pre-filled a drop down box with dynamic values. The values in $profession_type will change frequently (and will eventually be driven from a table in the db), so I can't do hard code it.

EDIT: Sorry my question was unclear.

Is that more clear? Sorry.

Any suggestions?

Upvotes: 0

Views: 1655

Answers (2)

sk29910
sk29910

Reputation: 2345

This goes in your .php file:

<!-- some HTML here -->

<?php
$profession_type = [result_from_database_query] ?>

<!-- more HTML here -->

<select name="profession_type">
<?php
   foreach ($profession_type as $p){
        print "<option value='" . $p . "'>" . $p . "</option>";
    }
?>
</select>

Upvotes: 1

poplitea
poplitea

Reputation: 3737

How about this:

print '<select name="profession_type">';
print '<option value=""></option>';
foreach ($profession_type as $p)
{
    if ($p == $chosen_profession)
        print "<option value='" . $p . "' selected='selected'>" . $p . "</option>";
    else
        print "<option value='" . $p . "'>" . $p . "</option>";
}
print '</select>';

Upvotes: 2

Related Questions