如何使单选按钮返回布尔值true / false而不是on / off

如何使单选按钮返回布尔值true / false而不是on / off

问题描述:

I want that my radio buttons return me a Boolean value true or false instade of on/off

So I pass the true/false in the value of the input :

<label>Male
   <input type="radio" name="IsMale" value="true" />
</label> 
<label>Female
   <input type="radio" name="IsMale" value="false" />
</label>

but it returns me a true/false in a text format. Please masters how could I get them in a booleen format ?

More details : In fact I need to store my $_POST array in a file.txt, and for my radio button I need to store for example :

array ( "IsMale" => true );

and not :

array ( "IsMale" => "true" );

You'll have to check the data and modify it.

if(isset($_POST['SubmitButton'])) { 

  $_POST['IsMale'] = $_POST['IsMale'] == 'true' ? true : false;
}

You cannot make radio buttons or any other form element directly submit a PHP true value, only a string such as "true".

To solve your problem, you would have to change the value of the $_POST item in your PHP file.

//Form has been submitted
if(isset($_POST['submit'])) {

    //Radio button has been set to "true"
    if(isset($_POST['IsMale']) && $_POST['IsMale'] == 'true') $_POST['IsMale'] = TRUE;

    //Radio button has been set to "false" or a value was not selected
    else $_POST['IsMale'] = FALSE;

}

Edit: Ben has provided a functional solution using ternary operators which is a shorter alternative. The example above may clarify exactly what is going on in the process (in a more verbose form).