YKJ
YKJ

Reputation: 149

How to set select to multiple select

I have select box with multiple select. I have an array with value. I want to set selected values of select field based on array.
I have an array

values=array("a","b","c","d","e");

And select field

    <select name="check[]" id="check" multiple> 
        <option value="">--- Select Document Type ----</option>
        <option value="a">a</option>
        <option value="b">b</option>
        <option value="c">c</option>
        <option value="d">d</option>
        <option value="e">e</option>
        <option value="f">f</option>
        <option value="g">g</option>
        <option value="h">h</option>
    </select>

I want options selected as per array.

Upvotes: 0

Views: 117

Answers (3)

Kevin
Kevin

Reputation: 41885

You can use in_array() in this case:

$values=array("a","b","c","d","e");
$select = range('a', 'h');

?>
<select name="check[]" multiple="multiple" style="width: 100px; height: 200px;">
    <?php foreach($select as $s): ?>
        <option value="<?php echo $s; ?>" <?php echo in_array($s, $values) ? 'selected' : ''; ?> >
            <?php echo $s; ?>
        </option>
    <?php endforeach; ?>
</select>

Fiddle

Upvotes: 2

Salini L
Salini L

Reputation: 879

I am not sure what you want. Check whether you want this

<?php
$values=array("a","b","c","d","e");
?>
<select name="check[]" id="check" multiple> 
        <option value="">--- Select Document Type ----</option>
        <?php
        foreach ($values as $x)
        {
            ?>
             <option value="<?php echo $x; ?>"><?php echo $x; ?></option>
             <?php
        }
        ?>
    </select>

Upvotes: 0

Aleksandr Mochalygin
Aleksandr Mochalygin

Reputation: 18

foreach ($values as $key=>$value)
    echo '<option value="'.$key.'">'.$value.'</option>';

Upvotes: 0

Related Questions