php 如何使单选按钮返回布尔值真/假而不是开/关

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13968827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:22:16  来源:igfitidea点击:

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

phparraysradio-button

提问by Sami El Hilali

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

我希望我的单选按钮返回一个布尔值 true 或 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 :

更多细节:事实上,我需要将我的 $_POST 数组存储在 file.txt 中,对于我的单选按钮,我需要存储例如:

array ( "IsMale" => true );

and not :

并不是 :

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

回答by Ben Fransen

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

你必须检查数据并修改它。

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

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

回答by Dan Greaves

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

您不能让单选按钮或任何其他表单元素直接提交 PHP 真值,只能提交诸如“true”之类的字符串。

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

要解决您的问题,您必须更改 PHP 文件中 $_POST 项目的值。

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

编辑:Ben 提供了一个使用三元运算符的功能解决方案,这是一个更短的替代方案。上面的例子可以清楚地说明过程中发生了什么(以更详细的形式)。