ctype_digit

(PHP 4 >= 4.0.4, PHP 5)

ctype_digit -- Check for numeric character(s)

说明

bool ctype_digit ( string text )

Checks if all of the characters in the provided string, text, are numerical.

参数

text

The tested string.

返回值

Returns TRUE if every character in text is a decimal digit, FALSE otherwise.

范例

例子 1. A ctype_digit() example

<?php
$strings
= array('1820.20', '10002', 'wsl!12');
foreach (
$strings as $testcase) {
    if (
ctype_digit($testcase)) {
        echo
"The string $testcase consists of all digits.\n";
    } else {
        echo
"The string $testcase does not consist of all digits.\n";
    }
}
?>

上例将输出:

The string 1820.20 does not consists of all digits.
The string 10002 consists of all digits.
The string wsl!12 does not consists of all digits.


add a note add a note User Contributed Notes
kitchin
14-Oct-2006 10:36
Confirming Crimson's bug in 4.3.10, Windows and Linux.  It affects all the ctype_ functions.

It is caused by this bug handling large numbers,
http://bugs.php.net/bug.php?id=34645
fixed in 4.4.1.  I tested Crimson's code in 4.4.4 Windows and it now works.

Also note ctype_ treats small integers as ASCII codes, not strings.  So ctype_digit(109) is false, but ctype_digit('109') is true.  Large integers (>255) are treated as strings.
crimson at technologist dot com
12-Sep-2005 06:05
In PHP 4.3.11 (not sure about other versions), this function can provide erratic behavior. Though we normally expect automatic type casting to do the work for us, in these ctype functions, you must do it yourself!

Example:
<?php
  
echo '<pre>';

  
$fields[0] = 'somestring';
  
$fields[1] = 150679;
  
$fields[2] = 20050912;

  
var_dump($fields);
  
   if(!
ctype_digit($fields[1])) echo "1 not digits\n";
   if(!
ctype_digit($fields[2])) echo "2 not digits\n";

  
var_dump($fields);

   echo
'</pre>';
?>

Returns:
array(3) {
  [0]=>
  string(10) "somestring"
  [1]=>
  int(150679)
  [2]=>
  int(20050912)
}
array(3) {
  [0]=>
  string(10) "somestring"
  [1]=>
  string(8) "20050912"
  [2]=>
  int(20050912)
}

Notice that the value in $fields[2] was converted to a string and moved to $fields[1]! Explicitly converting the values to strings solved the problem.
info at challengia dot com
12-Jan-2005 06:25
Note : ctype_digit(1) return false. So if you use it against an unknown type, cast you var to string first -- ctype_digit((string)$myvar).