ctype_digit

(PHP 4 >= 4.0.4, PHP 5)

ctype_digit -- Проверяет является ли символ цифрой

Описание

bool ctype_digit ( string text )

Возвращает TRUE если каждый символ строки text является десятичной цифрой, либо FALSE в противном случае.

Пример 1. Пример использования функции ctype_digit()

<?php
$strings
= array('1820.20', '10002', 'wsl!12');
foreach (
$strings as $testcase) {
   if (
ctype_digit($testcase)) {
       echo
"Строка $testcase состоит только из цифр.\n";
   } else {
       echo
"Строка $testcase не состоит только из цифр.\n";
   }
}
?>

Этот пример выведет :

Строка 1820.20 не состоит только из цифр.
Строка 10002 состоит только из цифр.
Строка wsl!12 не состоит только из цифр.

Смотрите также ctype_alnum() и ctype_xdigit().



ctype_digit
GamblerZG
12-Sep-2005 11:30
My function:
<?php
function isDigital($var){
   return (!empty(
$var) && (is_string($var) || is_int($var)) && ctype_digit((string) $var));
}
?>
It returns true only when given positive integer or string that contains only digits.
crimson at technologist dot com
12-Sep-2005 03: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 02: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).

<ctype_cntrlctype_graph>
 Last updated: Tue, 15 Nov 2005