检查正整数(PHP)的最佳方法? [英] Best way to check for positive integer (PHP)?

查看:59
本文介绍了检查正整数(PHP)的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查表单输入值是否为正整数(而不仅仅是整数),并且我注意到使用以下代码的另一个代码段:

I need to check for a form input value to be a positive integer (not just an integer), and I noticed another snippet using the code below:

$i = $user_input_value;
if (!is_numeric($i) || $i < 1 || $i != round($i)) {
  return TRUE;
}

我想知道使用上面的三项检查是否有任何优势,而不仅仅是这样做:

I was wondering if there's any advantage to using the three checks above, instead of just doing something like so:

$i = $user_input_value;
if (!is_int($i) && $i < 1) {
  return TRUE;
}

推荐答案

两个代码段之间的区别在于,如果$ i是数字字符串,则is_numeric($i)也会返回true,但是仅在$ i是整数时返回true,而在$ i是整数字符串时不返回.这就是为什么如果$ i是整数字符串(例如,如果$ i =="19"而不是$ i == 19)也要返回true,则应该使用第一个代码段的原因.

the difference between your two code snippets is that is_numeric($i) also returns true if $i is a numeric string, but is_int($i) only returns true if $i is an integer and not if $i is an integer string. That is why you should use the first code snippet if you also want to return true if $i is an integer string (e.g. if $i == "19" and not $i == 19).

有关更多信息,请参见以下参考资料:

See these references for more information:

php is_numeric函数

php is_int函数

这篇关于检查正整数(PHP)的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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