使用PHP检查变量是否包含正整数的最短方法? [英] Shortest way to check if a variable contains positive integer using PHP?

查看:57
本文介绍了使用PHP检查变量是否包含正整数的最短方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查用户是否输入了正整数.

I want to check if user input a positive integer number.

1    = true
+10  = true
.1   = false
-1   = false
10.5 = false


Just a positive number. 
No characters.
No special character.
No dot.
No minus sign.

我尝试了is_int()函数,但是即使在正整数上也返回false.是否有 int字符串问题?

I tried is_int() function but it is returning false even on positive integers. Is there a string to int problem?

推荐答案

类似的东西应该可以工作.将值转换为整数并将其与原始格式进行比较(因为我们使用==而不是===,因此PHP在检查相等性时会忽略类型).然后我们知道它是一个整数,我们测试它是否>0.(取决于您对正数的定义,您可能需要>= 0)

Something like this should work. Cast the value to an integer and compare it with its original form (As we use == rather than === PHP ignores the type when checking equality). Then as we know it is an integer we test that it is > 0. (Depending on your definition of positive you may want >= 0)

$num = "20";

if ( (int)$num == $num && (int)$num > 0 )

这篇关于使用PHP检查变量是否包含正整数的最短方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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