2012-12-20 09:23 阅读 88

如何使单选按钮返回布尔值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 :

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

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" );
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dongmao7195 dongmao7195 2012-12-20 09:25

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

    if(isset($_POST['SubmitButton'])) { 
      $_POST['IsMale'] = $_POST['IsMale'] == 'true' ? true : false;
    点赞 评论 复制链接分享
  • duan051347 duan051347 2012-12-20 09:29

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

    点赞 评论 复制链接分享