Make Selected Mutiselect Items “selected”

I’m assuming your $selected variable contains an array of values for the currently selected items?

You can’t use selected in this case (with multi select boxes) because it only compares two strings. It won’t test to see if the value is in an array. Instead, use a ternary statement and in_array()

<?php 
foreach ($cats as $cat_list ) { 
$selected = in_array( $cat_list->cat_ID, $selected ) ? ' selected="selected" ' : '';    
?>
    <option value="<?php echo $cat_list->cat_ID; ?>" <?php echo $selected; ?>><?php echo $cat_list->cat_name; ?></option> 
<?php } ?>

Leave a Comment