PHP 中的 ctype_digit() 函數用於檢查文本的每個字符是否為數字。如果字符串的所有字符都是數字,則返回 TRUE,否則返回 FALSE。
用法:
ctype_digit(string text)
使用的參數:
PHP 中的 ctype_digit() 函數隻接受一個參數。
- text:它的強製參數指定了被測試的字符串。
返回值:
如果字符串的所有字符都是數字,則返回 TRUE,否則返回 FALSE。
錯誤和異常:
- 傳遞字符串時給出預期結果,傳遞整數時不給出所需輸出。
- 該函數在 PHP 5.1.0 之前版本的空字符串上返回 true
例子:
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() 函數。
<?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";
}
?>
輸出:
Yes
節目:2
驅動代碼 ctype_digit() 函數,其中輸入將是包含特殊字符、整數、字符串的字符串數組。
<?php
// PHP program to check is given string
// contains all digits using ctype_digit
$strings = array(
'Geeks-2018',
'geek@yahoo.com',
'10.99999Fe',
'12345',
'geeksforgeeks.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";
}
}
?>
輸出:
No No No Yes No
ctype_digit() 對比 is_int()
ctype_digit() 本質上用於字符串類型,而 is_int() 用於整數類型。 ctype_digit() 遍曆所有字符並檢查每個字符是否為數字。例如,
<?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";
?>
輸出:
No Yes
參考資料:http://php.net/manual/en/function.ctype-digit.php
注:本文由純淨天空篩選整理自GeeksforGeeks大神的英文原創作品 PHP | ctype_digit() (Checks for numeric value)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。