Rob*_*ble 88
is_int()如果参数是整数类型,ctype_digit()则返回true,如果字符串中的所有字符都是数字,则返回字符串参数并返回true.
例:
?????????????????????????????????????????
? ? is_int: ? ctype_digit: ?
?????????????????????????????????????????
? 123 ? true ? false ?
?????????????????????????????????????????
? 12.3 ? false ? false ?
?????????????????????????????????????????
? "123" ? false ? true ?
?????????????????????????????????????????
? "12.3" ? false ? false ?
?????????????????????????????????????????
? "-1" ? false ? false ?
?????????????????????????????????????????
? -1 ? true ? false ?
?????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
is_numeric如果传入的值可以解析为数字,则还有返回 true 。
如果我尝试在PHP 5.5.30上比较函数的性能,结果如下:
这是我用于基准测试的代码
// print table cell and highlight if lowest value is used
function wr($time1, $time2, $time3, $i) {
if($i == 1) $time = $time1;
if($i == 2) $time = $time2;
if($i == 3) $time = $time3;
echo('<td>');
if(min($time1, $time2, $time3) === $time) printf('<b>%.4f</b>', $time);
else printf('%.4f', $time);
echo('</td>');
}
$test_cases = array( 123, 12.3, '123', true);
$tests = 1000000;
$result = true; // Used just to make sure cycles won't get optimized out
echo('<table>'.PHP_EOL);
echo('<tr><td> </td><th>is_int</th><th>ctype_digit</th><th>is_numeric</th></tr>');
foreach($test_cases as $case) {
echo('<tr><th>'.gettype($case).'</th>');
$time = microtime(true);
for($i = 0; $i < $tests; $i++) {
$result |= is_int((int)rand());
}
$time1 = microtime(true)-$time;
$time = microtime(true);
for($i = 0; $i < $tests; $i++) {
$result |= ctype_digit((int)rand());
}
$time2 = microtime(true)-$time;
$time = microtime(true);
for($i = 0; $i < $tests; $i++) {
$result |= is_numeric((int)rand());
}
$time3 = microtime(true)-$time;
wr($time1, $time2, $time3, 1);
wr($time1, $time2, $time3, 2);
wr($time1, $time2, $time3, 3);
echo('</tr>'.PHP_EOL);
}
echo('</table>');
exit();
Run Code Online (Sandbox Code Playgroud)