这肯定对微土地标题优化,但嘿:我正在努力的代码每天咀嚼数百万件物品,现在是星期五。所以,我没有尝试一点点......
for ($i = 0; $i < 1000000; $i++) {
// Option 1: simple casting/equivalence testing
if ((int) $value == $value && $value > 0) { ... }
// Option 2: using is_int() and ctype_digit(). Note that ctype_digit implicitly rejects negative values!
if ((is_int($value) && $value > 0) || ctype_digit($value)) { ... }
// Option 3: regular expressions
if (preg_match('/^\d+$/', $value)) { ... }
}
我然后跑两个整数上面的测试和字符串值
选项1:简单的铸件/等价测试
选项2:使用is_int()和ctype_digit()
方案3:正则表达式
也许并不奇怪,选项1是目前为止最快的,因为有没有函数调用,只是投射。另外值得一提的是,与其它方法不同,选项1个将字符串浮整数值“5.0”作为一个整数:
$valList = array(5, '5', '5.0', -5, '-5', 'fred');
foreach ($valList as $value) {
if ((int) $value == $value && $value > 0) {
print "Yes: " . var_export($value, true) . " is a positive integer\n";
} else {
print "No: " . var_export($value, true) . " is not a positive integer\n";
}
}
Yes: 5 is a positive integer
Yes: '5' is a positive integer
Yes: '5.0' is a positive integer
No: -5 is not a positive integer
No: '-5' is not a positive integer
No: 'fred' is not a positive integer
无论这是否是您的特定用例是一件好事留作练习读者...
最后一次检查是只看到如果数字是一个整数。使用此检查真的取决于您的要求 – Ass3mbler 2011-01-30 19:22:22
...您正在检查代码中的负数。 – JeroenEijkhof 2011-01-30 19:26:56
固定!对于那个很抱歉。 – geerlingguy 2011-01-30 19:36:19