How to make a radio button return boolean true/false instead of on/off
Asked Answered
T

2

13

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" );
Taxable answered 20/12, 2012 at 9:23 Comment(0)
M
21

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

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

  $_POST['IsMale'] = $_POST['IsMale'] == 'true' ? true : false;
}
Micron answered 20/12, 2012 at 9:25 Comment(1)
Yeah that's the only way. You can't get a boolean from the POST data.Pariah
A
3

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).

Arrio answered 20/12, 2012 at 9:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.