如何获得int而不是字符串形式? [英] How to get int instead string from form?

查看:160
本文介绍了如何获得int而不是字符串形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从表单获取变量:

 < form method ='POST'action =''> 
< input type ='text'name ='a'size ='1'>
< input type ='submit'value ='找到它'>

如果我输入1并使用gettype($ POST_ [ 'a'])它返回我的字符串,是否可以输入int?因为在这之后我想检查该变量是否为int。



UPDATE <

得到的答案总是返回字符串,他们让我使用(int)或intval(),但是如果它真的是字符串'a',它会返回0,但也可能是整数值0,如何克服这个问题?

更新



编辑错字后,Brad Christie建议使用is_numeric的最佳方式

解决方案

  //将$ _POST ['a']转换为整数,如果它是有效的,或者默认为0 
$ int =(is_numeric($ _ POST ['a'])?(int)$ _ POST ['a']] :0);

您可以使用 is_numeric 来检查,并且php允许转换为整数类型。



要进行实际比较,您可以执行 is_int



更新

5.2版 filter_input 对于这种数据类型(和其他类型)来说可能更健壮一些:

  $ int = filter_input(INPUT_POST,'a',FILTER_VALIDATE_INT); 

我选择了 FILTER_VALIDATE_INT ,但也有 FILTER_SANITIZE_NUMBER_INT 更多 - 这取决于你想要做什么。


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.

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?

UPDATE

After editing typo Brad Christie suggested best way, using is_numeric

解决方案

// 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_numeric to check, and php allows casting to integer type, too.

For actual comparisons, you can perform is_int.

Update

Version 5.2 has filter_input which may be a bit more robust for this data type (and others):

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

这篇关于如何获得int而不是字符串形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆