检查提交单选按钮 - PHP

I need to check a radio button input on submit.

If none of the radio buttons are checked, $err1_diet gets set to true and the red class needs to be added.

And I also need to know which radio button was checked since this isn't the only question in the form.

  if( !isset($_POST['diet']) ){
    $err1_diet = true;
  }elseif($_POST['diet'] == 1){
    $diet = true;
  }else{
    $diet = false;
    $yes = true;
  }

<p class="<?php echo (($err1_diet == true) ? "red" : "" ); ?>">&#8226; Are you on a diet?<?php var_dump($err1_diet); ?></p>
<input type="radio" name="diet" value="1" <?php echo (($diet) ? 'checked="true"' : "" ); ?> /> Yes
<input type="radio" name="diet" value="0" <?php echo (($diet) ? '' : 'checked="true"' ); ?> /> No

Actually no ... it's checking one of the radio buttons before the form is submitted. That's the problem

You can solve your problem using $_SERVER['REQUEST_METHOD']=='POST' for example:

if( $_SERVER['REQUEST_METHOD']=='POST' and !isset($_POST['diet']) ){
    $err1_diet = true;
  }elseif($_POST['diet'] == 1){
    $diet = true;
  }else{
    $diet = false;
    $yes = true;
  }

<p class="<?php echo (($err1_diet == true) ? "red" : "" ); ?>">&#8226; Are you on a diet?<?php var_dump($err1_diet); ?></p>
<input type="radio" name="diet" value="1" <?php echo (($diet) ? 'checked="true"' : "" ); ?> /> Yes
<input type="radio" name="diet" value="0" <?php echo (($diet) ? '' : 'checked="true"' ); ?> /> No