ctype_digit

(PHP 4 >= 4.0.4, PHP 5)

ctype_digitПроверяет на наличие цифровых символов в строке

Описание

bool ctype_digit ( string $text )

Проверяет, являются ли все символы в строке text цифровыми.

Список параметров

text

Проверяемая строка.

Возвращаемые значения

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

Список изменений

Версия Описание
5.1.0 До версии PHP 5.1.0 эта функция возвращала TRUE, если в качестве text передавалась пустая строка.

Примеры

Пример #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 не состоит только из цифр.

Пример #2 Пример использования ctype_digit() со сравнением строк и целых чисел

<?php

$numeric_string 
'42';
$integer        42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 это символ * )

is_numeric($numeric_string);   // true
is_numeric($integer);          // true
?>

Примечания

Замечание:

Для извлечения пользы из работы этой функции ей необходимо передавать строку (string), поэтому, если ей, к примеру, будет передан integer, то она может не возвратить ожидаемый результат. Однако, необходимо учитывать, что HTML-формы передают числовые строки, а не целые числа. Подробнее читайте в разделе "Типы" данного руководства.

Смотрите также

  • ctype_alnum() - Проверяет на наличие буквенно-цифровых символов
  • ctype_xdigit() - Проверяет наличие шестнадцатиричных цифр
  • is_numeric() - Проверяет, является ли переменная числом или строкой, содержащей число
  • is_int() - Проверяет, является ли переменная переменной целочисленного типа
  • is_string() - Проверяет, является ли переменная строкой

Коментарии

Also note that

<?php ctype_digit("-1");   //false ?>
2009-05-24 21:17:44
http://php5.kiev.ua/manual/ru/function.ctype-digit.html
Автор:
Note that an empty string is also false:
ctype_digit("") // false
2009-07-18 06:53:22
http://php5.kiev.ua/manual/ru/function.ctype-digit.html
ctype_digit() will treat all passed integers below 256 as character-codes. It returns true for 48 through 57 (ASCII '0'-'9') and false for the rest.

ctype_digit(5) -> false
ctype_digit(48) -> true
ctype_digit(255) -> false
ctype_digit(256) -> true

(Note: the PHP type must be an int; if you pass strings it works as expected)
2009-12-14 10:41:41
http://php5.kiev.ua/manual/ru/function.ctype-digit.html
Автор:
Using is_numeric function is quite faster than ctype_digit.

is_numeric took 0.237 Seconds for one million runs. while ctype_digit took 0.470 Seconds.
2010-02-05 07:38:17
http://php5.kiev.ua/manual/ru/function.ctype-digit.html
is_numeric gives true by f. ex. 1e3 or 0xf5 too. So it's not the same as ctype_digit, which just gives true when only values from 0 to 9 are entered.
2010-05-21 15:44:35
http://php5.kiev.ua/manual/ru/function.ctype-digit.html
All basic PHP functions which i tried returned unexpected results. I would just like to check whether some variable only contains numbers. For example: when i spread my script to the public i cannot require users to only use numbers as string or as integer. For those situation i wrote my own function which handles all inconveniences of other functions and which is not depending on regular expressions. Some people strongly believe that regular functions slow down your script.

The reason to write this function:
1. is_numeric() accepts values like: +0123.45e6 (but you would expect it would not)
2. is_int() does not accept HTML form fields (like: 123) because they are treated as strings (like: "123").
3. ctype_digit() excepts all numbers to be strings (like: "123") and does not validate real integers (like: 123).
4. Probably some functions would parse a boolean (like: true or false) as 0 or 1 and validate it in that manner.

My function only accepts numbers regardless whether they are in string or in integer format.
<?php
   
/**
     * Check input for existing only of digits (numbers)
     * @author Tim Boormans <info@directwebsolutions.nl>
     * @param $digit
     * @return bool
     */
   
function is_digit($digit) {
        if(
is_int($digit)) {
            return 
true;
        } elseif(
is_string($digit)) {
            return 
ctype_digit($digit);
        } else {
           
// booleans, floats and others
           
return false;
        }
    }
?>
2012-05-20 00:16:19
http://php5.kiev.ua/manual/ru/function.ctype-digit.html
Interesting to note that you must pass a STRING to this function, other values won't be typecasted (I figured it would even though above explicitly says string $text).

I.E.

<?PHP
$val 
42//Answer to life
$x ctype_digit($val);
?>

Will return false, even though, when typecasted to string, it would be true.

<?PHP
$val 
'42';
$x ctype_digit($val);
?>

Returns True.

Could do this too:

<?PHP
$val 
42;
$x ctype_digit((string) $val);
?>

Which will also return true, as it should.
2013-04-25 21:04:18
http://php5.kiev.ua/manual/ru/function.ctype-digit.html
I just wanted to clarify a flaw in the function is_digit() suggested by "info at directwebsolutions dot nl " .. 
It returns true in case of negative integers and false in case of strings that contain negative integers .
 example:
is_digit(-10); // returns ture
is_digit('-10'); // returns false
2015-10-03 04:41:49
http://php5.kiev.ua/manual/ru/function.ctype-digit.html
Please note that ctype_digit() will say true for strings such as '00001', which are not technically valid representations of integers, while saying false to strings such as '-1', which are. It's basically a faster version of the regex /^\d+$/. As the name says, it answers the question "does this string contain only digits" literally. It does not answer "is this a valid representation of an integer". If that's what you want, use is_int(filter_var($val, FILTER_VALIDATE_INT)) instead.
2015-10-07 16:21:02
http://php5.kiev.ua/manual/ru/function.ctype-digit.html

    Поддержать сайт на родительском проекте КГБ