根据php变量检查单选按钮

时间:2019-02-06 03:00:49

标签: php html html5 radio-button

我能够通过php变量设置文本字段的值,以便刷新页面时,文本字段会像下面这样填充:

<td><input type="text" name="user" value="<?php echo ($_REQUEST['user']); ?>" /></td>

但是,我想对具有不同变量$gender的单选按钮执行相同的操作。我该怎么办?

<td><input type="radio" name="gender" value="male"> Male<br>
                    <input type="radio" name="gender" value="female"> Female<br>
                    <input type="radio" name="gender" value="other"> Other</td>

2 个答案:

答案 0 :(得分:2)

这称为ternary operator

<?php

'<td><input type="radio" name="gender" value="male" '.($_REQUEST['gender'] == "male" ? 'checked' : '').'> Male<br>
     <input type="radio" name="gender" value="female" '.($_REQUEST['gender'] == "female" ? 'checked' : '').'> Female<br>
     <input type="radio" name="gender" value="other" '.($_REQUEST['gender'] == "other" ? 'checked' : '').'> Other</td>'

?>

答案 1 :(得分:2)

如果要针对多个无线电组自动执行此操作,则可以编写一个函数:

<?php
declare (strict_types=1);

function radio_buttons(string $name, array $values_labels, int $indent = 4)
{
  $ind = str_repeat(' ', $indent);
  foreach ($values_labels as $value => $label)
  {
    $checked = ($_REQUEST[$name] ?? '') === $value ? ' checked' : '';
    echo <<<__EOF__
$ind<input type="radio" id="radio-$name-$value" name="$name" value="$value"$checked><label for="radio-$name-$value">$label</label>

__EOF__;
  }
}

?>
<body>
  <form>
<?php radio_buttons('gender', ['male' => 'Male', 'female' => 'Female', 'other' => 'Other'], 4); ?>
    <button type="submit">submit</button>
  </form>
</body>