John Davidson

php - adding selected attribute to dropdownlist item if is in array


I have code table like this.


I'm adding this codes as array from dropdown list to assigned_code column in the user table.


When I want to edit the codes assigned to the user, I need to add selected attribute which codes are assigned previously in dropdown list. I'm stuck at this point. Can anyone show me the how to do this?

$assigned_code = array();

$sql = "select assigned_code from user where ID=1";
$rq = mysqli_query($conn, $sql);
$count = mysqli_num_rows($rq);
if ($count>0) {
while ($row = mysqli_fetch_array($rq)) {

<select name="u_codes[]" id="u_codes" class="selectpicker" multiple="multiple">

$sql = "select code,desc from codes";
$rq = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($rq)) {
$code = $row["code"];
$codeDesc = $row["desc"];
if ($assigned_code == $code) {
echo '<option value="'.$code.'" selected="selected">'.$codeDesc.'</option>';
} else {
echo '<option value="'.$code.'">'.$codeDesc.'</option>';


My Answer:
You can achieve this by looping through the dropdown list options and checking if the code is in the array of assigned codes. If it is, you can add the selected attribute to that option.

Here is an example code snippet to demonstrate this:

// Array of assigned codes
$assigned_codes = ['00', '02', '03'];

// Dropdown list options
$options = ['00', '01', '02', '03'];

// Loop through the options and add selected attribute if code is in assigned codes
foreach ($options as $option) {
if (in_array($option, $assigned_codes)) {
echo '';
} else {
echo '';

In this code snippet, we first define the array of assigned codes and the dropdown list options. We then loop through the options and check if each option is in the array of assigned codes. If it is, we add the selected attribute to that option. Otherwise, we just output the option without the selected attribute.

You can modify this code snippet to fit your specific implementation and integrate it into your form for editing the assigned codes.

Rate this post

3 of 5 based on 2922 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us