ctype_digit()(检查数值)
PHP中的一个ctype_digit()函数,用于检查文本的每个字符是否为数字。如果字符串的所有字符都是数字,则返回TRUE,否则返回FALSE。
语法
1 | ctype_digit(string text) |
参数使用:PHP中的ctype_digit()函数只接受一个参数。
- text:指定测试字符串的强制参数。
返回值:如果字符串的所有字符都是数字,则返回TRUE,否则返回FALSE。
1 2 3 4 5 6 7 8 | Input :789495001 Output : Yes Explanation : All digits, return True Input : 789.0877 Output : No Explanation: String contains floating point, return false. |
下面的程序演示了ctype_digit()函数。
程序:1检查包含所有数字的单个字符串的ctype_digit()函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php // PHP program to check given string is // control character $string = '123456789'; // Checking above given string // by using of ctype_digit() function. if ( ctype_digit($string)) { // if true then return Yes echo "Yes\n"; } else { // if False then return No echo "No\n"; } ?> |
输出
1 | Yes |
程序2:驱动一个代码ctype_digit()函数,其中的输入将是包含特殊字符、整数和字符串的字符串数组。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <?php // PHP program to check is given string // contains all digits using ctype_digit $strings = array( 'Geeks-2018', 'skyg@yahoo.com', '10.99999Fe', '12345', 'love.org' ); // Checking above given strings //by used of ctype_digit() function . foreach ($strings as $testcase) { if (ctype_digit($testcase)) { // if true then return Yes echo "Yes\n"; } else { // if False then return No echo "No\n"; } } ?> |
输出
1 2 3 4 5 | No No No Yes No |
ctype_digit() vs is_int()
ctype_digit()基本上用于字符串类型,is_int()用于整数类型。ctype_digit()遍历所有字符并检查每个字符是否是数字。例如,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php // PHP code to demonstrate difference between // ctype_digit() and is_int(). $x = "-123"; if (ctype_digit($x)) echo "Yes\n"; else echo "No\n"; $x = -123; if (is_int($x)) echo "Yes"; else echo "No"; ?> |
输出
1 2 | No Yes |
参考