0

I am trying to display a select box with multiple select

I have two array one for option value $course another for $selected_course

here is my code kindly review it and inform me where I have done my mistake.

$course =stdClass Object
(
    [Id] => 4
    [name] => EME
    [desc] => 
    [details] => 
    [created_by] => 0
    [created_on] => 2016-01-01 23:47:15
    [ip] => 
    [status] => 0
)

$selected_course= Array
(
    [0] => 4
    [1] => 2
)

Now here is my code:

<?php     
    $i=0;
    foreach ($courses as $course) {
    $select_Course=explode(',',$center->course) ;
?>
    <option <?php echo (isset($select_Course[$i]) || $select_Course[$i]==$course->Id)?'selected':false;?>  value="<?=$course->Id;?>"><?=$course->name;?></option>
<?php 
    $i++;
} ?>

Its not selecting anyone of them why ?? I have tried in_array , array_search but failed

3
  • just check what you get in $select_Course[$i] and $course->Id. Commented Jan 2, 2016 at 9:25
  • now i have change my logic <option <?php echo (array_search($course->Id, $select_Course))?'selected':false;?> but its also not giving me the proper result Commented Jan 2, 2016 at 9:32
  • So the $courses array contains all $course object, right? Commented Jan 2, 2016 at 9:39

1 Answer 1

2

If $courses array contains all the course objects, then your code should be like this:

<select multiple>
    <?php
        foreach($courses as $course){
            $option = "<option value=\"{$course->Id}\"";
            if(in_array($course->Id, $selected_course)){
                $option .= " selected";
            }
            $option .= ">{$course->name}</option>";
            echo $option;
        }
    ?>
</select>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Man . Its Works Perfectly .

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.