2

In PHP, I am having 2 array

$ex1 = array(a,b,c,d,e,f,g,h);
$ex2 = array(c,e,f);

Here how can I integrate this with multiple select option in PHP page

Here ex1 is the multiple select array like

<select multiple name=slt[]>

</select>

And ex2 values are the chosen listing options

0

3 Answers 3

2

Something like:

<?php

$ex1 = array('a','b','c','d','e','f','g','h');
$ex2 = array('c','e','f');

echo "<select multiple name=slt[]>";

    foreach($ex1 as $val){
        //in_array() checks if value from 1st array ($val) is present
        //anywhere in the second array ($ex2)
        //if yes, that option will be selected. I'm using ternary operator 
        //here instead of if statement
        $selected = (in_array($val,$ex2))?' selected':'';
        echo "<option value='".$val."'$selected>".$val."</option>";
    }

echo "</select>";


?>

PHP Demo

Output Fiddle

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

1 Comment

@user2688251 You're welcome, added a bit of comment to read if you're interested to learn.
0

I'm not sure about what you want to do, but here's an idea :

$ex1 = array("a","b","c","d","e","f","g","h");

echo "<select multiple>";              
foreach( $ex1 as $value ){
    echo "<option value='$value'>$value</option>";
}

echo "</select>";

Comments

0

Try running it:

<?php
$ex1 = array('a','b','c','d','e','f','g','h');
$ex2 = array('c','e','f');
?>
<select multiple name=slt[]>
<?php
foreach ($ex1 as $option) {
    $active = false;
    foreach($ex2 as $selected){
        if($option == $selected){
            $active = true;
        }
    }
?>
    <option value="<?php echo $option; ?>" <?php if($active===true) echo "selected"; ?>><?php echo $option; ?></option>
<?php
}
?>
</select>

1 Comment

First array is the fields. And the $ex2 array values are selected fields. So it must highlight here

Your Answer

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