0

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? Commented Sep 22, 2014 at 10:35
  • I didnt understand. Do u want the array elements as ur dropdown options? Commented Sep 22, 2014 at 10:35
  • They say in_array should be helpful. Commented Sep 22, 2014 at 10:35

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.