php 如何从表单中获取 int 而不是 string?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5052932/
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
How to get int instead string from form?
提问by Templar
Getting variable from form:
从表单中获取变量:
<form method = 'POST' action = ''>
<input type = 'text' name = 'a' size = '1' >
<input type = 'submit' value = 'Find it'>
</form>"
If I enter 1 and use gettype($POST_['a']) it returns me string, is it possible to enter int? because after this I want check if that variable is int.
如果我输入 1 并使用 gettype($POST_['a']) 它返回我字符串,是否可以输入 int?因为在此之后我想检查该变量是否为 int。
UPDATE
更新
Got answers that it returns always string and they offered me to use (int) or intval(), but then if it's really string like 'a' it returns 0, but it may be also integer value 0, how to overcome this problem?
得到的答案是它总是返回字符串,他们让我使用 (int) 或 intval(),但是如果它真的是像 'a' 这样的字符串,它返回 0,但它也可能是整数值 0,如何克服这个问题?
UPDATE
更新
After editing typo Brad Christie suggested best way, using is_numeric
编辑错字后布拉德克里斯蒂建议最好的方法,使用 is_numeric
回答by Brad Christie
// convert the $_POST['a'] to integer if it's valid, or default to 0
$int = (is_numeric($_POST['a']) ? (int)$_POST['a'] : 0);
You can use is_numericto check, and php allows casting to integertype, too.
您可以使用is_numeric进行检查,并且 php 也允许转换为整数类型。
For actual comparisons, you can perform is_int.
对于实际比较,您可以执行is_int。
Update
更新
Version 5.2 has filter_input
which may be a bit more robust for this data type (and others):
5.2 版filter_input
对于这种数据类型(和其他数据类型)可能更健壮一点:
$int = filter_input(INPUT_POST, 'a', FILTER_VALIDATE_INT);
I chose FILTER_VALIDATE_INT
, but there is also FILTER_SANITIZE_NUMBER_INT
and a lot more--it just depends what you want to do.
我选择FILTER_VALIDATE_INT
,但也有FILTER_SANITIZE_NUMBER_INT
和很多更--IT只是取决于你想做的事情。
回答by jpsimons
Sending over the wire via HTTP, everythingis a string. It's up to your server to decide that "1" should be 1
.
通过 HTTP 通过网络发送,一切都是一个字符串。由您的服务器决定“1”应该是1
.
回答by Quentin
No. HTTP only deals with text (or binaries).
不。HTTP 只处理文本(或二进制文件)。
You have to convert it.
你必须转换它。
回答by Quentin
I'd use (int)$_POST['a']
to convert it to an integer.
我会(int)$_POST['a']
用来将其转换为整数。
回答by Simone Desantis
if you prefer mantain a wide type compatibility and preserve input types other than int (double, float, ecc.) i suggest something like this:
如果您更喜欢保持广泛的类型兼容性并保留除 int (double, float, ecc.) 以外的输入类型,我建议如下:
$var = is_numeric($_POST['a'])?$_POST['a']*1:$_POST['a'];
You will get:
你会得到:
$_POST['a'] = "abc"; // string(3) "abc"
$_POST['a'] = "10"; // int(10)
$_POST['a'] = "10.12"; // float(10.12)