2

I am able to set the value of a text field from a php variable so that when the page is refreshed, the text field remains filled in like so:

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

However, I would like to do the same for a radio button with a different variable, $gender. How could I do this?

<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>
Paradox
  • 4,602
  • 12
  • 44
  • 88
  • 1
    Possible duplicate of [How to select a radio button by default?](https://stackoverflow.com/questions/5592345/how-to-select-a-radio-button-by-default) – Pinke Helga Feb 06 '19 at 03:01
  • See duplicate, you can easily add the attribute conditionally on `$_REQUEST['gender'] === 'female'` – Pinke Helga Feb 06 '19 at 03:03

2 Answers2

3

This is called a 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>'

?>
Matthew
  • 3,136
  • 3
  • 18
  • 34
2

If you want to automate this for multiple radio groups, you could write a function:

<?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>
Pinke Helga
  • 6,378
  • 2
  • 22
  • 42