0
votes

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.

3
not clear what is the issue? - diEcho
I didnt understand. Do u want the array elements as ur dropdown options? - Salini L
They say in_array should be helpful. - raina77ow

3 Answers

2
votes

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

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

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>