php - Multiselect options not getting selected while editing existing data

I have a multi-select option, the selected option values of which are stored in a databsse as csv separated values like HJ,JB. While editing the data, i receive the value in a php variable as:
$usercenter = $row['user_center']; //HJ,JB
I am getting all thecenter_id
andcenter_value
items from the DB and all the options and values are displayed in dropdown. But the already selected values are not getting selected in code below:
<select id="center" name="center[]" multiple="multiple" size="5" tabindex="6">
<optgroup label=""><?php
$q = $conn->prepare("
SELECT center_id,center_name
FROM center
WHERE region = :region
&& status = :status
");
$q->execute(array(':region' => "$userregion",':status' => "Enabled"));
$data = $q->fetchAll(PDO::FETCH_ASSOC);
$myArray = explode(',', $usercenter); //original selected values ("HJ,JB")
foreach ($data as $opt) {
if(in_array($opt, $myArray)) {
$sel = ' selected="selected" ';
echo '<option ' . $sel . ' value="' . $opt['center_id'] . '">' . $opt['center_name'] . '</option>';
}else{
echo '<option value="' . $opt['center_id'] . '">' . $opt['center_name'] . '</option>';
}
}?>
</optgroup>
</select>
The issue seems like the database values in$row['user_center']
contains comma separated values of the select option. But the dropdown display contains both option names and values. Something is wrong with myin_array
comparison.
There are no errors. Dropdown displaying with all items. What am i doing incorrectly ?? Requesting help!!
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: composer detected issues in your platform: your composer dependencies require a php version ">= 7.3.0".
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.