dror shalit
dror shalit

Reputation: 318

Choosing selected values from array in select option tag

I have a for-each loop that populate multiple select option tag in edit mode, I would like to select the selected option that stored in the database.

The value from the DB is inside explode like this:

$f_r = explode(",",$user['field']);

This is my options create:

<?php  foreach ($fields as $field) : ?>
    <option value="<?= $field['field_name'] ?>" style="direction: rtl" ><?= $field['field_name'] ?></option>
<?php  endforeach; ?>

How can I select the values from the $f_r value ?

I have tried this code and I am getting the result but my list in the option tag is tippled based on the array result:

<select class="selectpicker form-control" name="field[]" id="field" multiple data-live-search="true">
  <?php $f_r = explode(",",$user['field']); ?>
  <!-- Array ( [0] => נדלן פרוייקטים [1] => נדלן פרטי [2] => נדלן פרטי ומסחרי )-->
  <?php  foreach ($fields as $field) : ?>
      <?php foreach ($f_r as $f) : ?>
          <option value="<?= $field['field_name'] ?>" style="direction: rtl" <?php if($f == $user['field']){echo 'selected';} ?> ><?= $field['field_name'] ? </option>
      <?php endforeach; ?>
  <?php  endforeach; ?>
</select>

How can I make it work without the option duplication?

Upvotes: 1

Views: 1111

Answers (1)

dWinder
dWinder

Reputation: 11642

I guess you could use in_array. Consider the following:

<?php  foreach ($fields as $field) : ?>
    <option value="<?= $field['field_name'] ?>" style="direction: rtl" <?php if(in_array($field['field_name'], $f_r)) {echo 'selected';} ?> ><?= $field['field_name'] ?></option>
<?php endforeach; ?>

Sorry for syntax - not on my computer but I hope you get the idea...

Upvotes: 1

Related Questions