更好的方法在PHP中执行此块

Mat*_*iby 5 php forms

我觉得必须有一个更好的方法来填充选定的....

<p>
    <label for="industry" class="medium">Industry</label>
    <select name="industry" >
        <option value="" selected="<?php if($_POST['industry'] =="") { echo "selected";} ?>">-- Select Industry --</option>
        <option value="Retail" selected="<?php if($_POST['industry'] =="Retail") { echo "selected";} ?>">Retail</option>
        <option value="Restaurant" selected="<?php if($_POST['industry'] =="Restaurant") { echo "selected";} ?>">Restaurant</option>
        <option value="Salon" selected="<?php if($_POST['industry'] =="Salon") { echo "selected";} ?>">Salon</option>
        <option value="Pizza Delivery" selected="<?php if($_POST['industry'] =="Pizza Delivery") { echo "selected";} ?>">Pizza Delivery</option>
        <option value="Grocery" selected="<?php if($_POST['industry'] =="Grocery") { echo "selected";} ?>">Grocery</option>
        <option value="Quick Service" selected="<?php if($_POST['industry'] =="Quick Service") { echo "selected";} ?>">Quick Service</option>
        <option value="Liquor Store" selected="<?php if($_POST['industry'] =="Liquor Store") { echo "selected";} ?>">Liquor Store</option>
        <option value="Tobacco" selected="<?php if($_POST['industry'] =="Tobacco") { echo "selected";} ?>">Tobacco</option>
        <option value="Video Store" selected="<?php if($_POST['industry'] =="Video Store") { echo "selected";} ?>">Video Store</option>
        <option value="Other" selected="<?php if($_POST['industry'] =="Other") { echo "selected";} ?>">Other</option>
    </select>
</p>
Run Code Online (Sandbox Code Playgroud)

rda*_*sky 6

您可以使用类似值创建数组

$options = array(
    'Retail', 'Restaurant', 'Salon'
);
Run Code Online (Sandbox Code Playgroud)

然后简单地for将值输出到表单中

<select name="industry">
    <?php for ($i = 0; $i < count($options); $i++) { ?>
    <option value="<?php echo $options[$i]; ?>"<?php echo $_POST['industry'] == $options[$i] ? ' selected="selected"' : ''; ?>><?php echo $options[$i]; ?></option>
    <?php } ?>
</select>
Run Code Online (Sandbox Code Playgroud)


fre*_*ley 3

通过创建$selected数组,您可以消除$_POST每次都必须检查的视觉和计算问题。

$selected = array();
$selected[$_POST['industry']] = "selected='selected'";
//all others will be nothing
$industries = array(); //populate with options

foreach($industries as $i){
  echo "<option value='$i' ".$selected[$i].">$i</option>";
}
Run Code Online (Sandbox Code Playgroud)