Taylor
Taylor

Reputation: 3141

PHP - Autopopulate multiple select field from arrary

Select input field can be automatically populated from the array. The array is a list of times.

For instance:

    $fruits = ['apple', 'mango', 'orange'];
    $input = '<select name="fruits" multiple="multiple">';
    foreach ($fruits as $key => $fruit) {
        if (is_array($selected_fruits)) {
            foreach ($selected_fruits as $f) {
                $selected = $f === $fruit ? 'selected="selected"' : '';
            }
        }
        $input .= "<option {$selected} value='{$key}'>$fruit</option>";
    }
    $input .= '</select>';

In the code above, the $selected_fruits are the fruits that user had selected and are stored in database. They are retrived as an array (e.g. ['orange', 'mango']). How can I best mark populate the field with the selected data from database?

Upvotes: 0

Views: 27

Answers (1)

smozgur
smozgur

Reputation: 1812

You can check if processing $fruit is in the $selected_fruits array in loop and set $selected variable accordingly.

$selected_fruits = ['orange', 'mango']; // Coming from your database, populate as empty array even there is no selected fruit coming from database
$fruits = ['apple', 'mango', 'orange'];
$input = '<select name="fruits" multiple="multiple">';
foreach ($fruits as $key => $fruit) {
    $selected = in_array($fruit, $selected_fruits) ? 'selected="selected"' : '';
    $input .= "<option {$selected} value='{$key}'>$fruit</option>";
}
$input .= '</select>';

Upvotes: 2

Related Questions