Php option value

前端 未结 4 1682
执念已碎
执念已碎 2021-01-07 03:44

I have a list of areas (1000+) and i was wondering if there was a way i can do this easier with code instead of repeating each value.


                        
    
提交评论

  • //pseudo
    $arr = array("apple", "lemon", "orange", ...);
    foreach($arr as $value) {
        echo '<option value="'.$value;
        if($user_data[$area] === $value) {
            echo 'selected';
        }
        //echo {the end of your option field syntax}
    }
    
    0 讨论(0)
  • 2021-01-07 04:28
    foreach ($areas as $key => $val)
    {
        $select.= '<option '; // opening the option tag
        foreach ($selected_from_db as $keyselected => $valselected)
        {
          $val_fetch_from_array = $valselected == $val['campaignid'] ? 'selected' : '';
          $select.= $val_fetch_from_array; // codes for selecting multiple values
        }
        $select.= ' value = "' . $val['campaignid'] . '">#' . $val['campaignid'] . '-' . $val['campaignname'] . '</option>'; // closing the option tag
    }
    
    0 讨论(0)
  • 2021-01-07 04:32

    All the solutions look good... Here's one more way though:

    <select>
    <?php
      $areas = array('apple', 'lemon', 'orange', 'banana');
      $areas_count = count($areas);
      for ($i = 0; $i < $areas_count; $i++) {
        echo '<option value="' . $areas[$i] . '"';
        echo ($user_data[$area] == $areas[$i]) ? ' selected' : '';
        echo '>' . ucwords($areas[$i]) . '</option>';
      }
    ?>
    </select>
    
    0 讨论(0)
  • 提交回复
    热议问题