ctype_digit

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_digitVerifica se os caracteres são numéricos

Descrição

ctype_digit(mixed $text): bool

Verifica se todos os caracteres na string fornecida, text, são numéricos.

Parâmetros

text

A string a ser testada.

Nota:

Se um int entre -128 e 255 inclusive for fornecido, ele será interpretado como o valor ASCII de um único caractere (valores negativos são somados a 256 para permitir caracteres no intervalo ASCII estendido). Qualquer outro inteiro será interpretado como uma string contendo os dígitos decimais do inteiro.

Aviso

A partir do PHP 8.1.0, passar um argumento que não seja string tornou-se defasado. No futuro, o argumento será interpretado como uma string em vez de um ponto de código ASCII. Dependendo do comportamento esperado, o argumento deve ser convertido para string ou uma chamada explícita para chr() deve ser feita.

Valor Retornado

Retorna true se todos caracteres na string text são dígitos decimais, false caso contrário. Quando chamada com uma string vazia, o resultado sempre será false.

Exemplos

Exemplo #1 Um exemplo de ctype_digit()

<?php
$strings
= array('1820.20', '10002', 'wsl!12');
foreach (
$strings as $caso_de_teste) {
if (
ctype_digit($caso_de_teste)) {
echo
"A string $caso_de_teste consiste inteiramente de dígitos.\n";
} else {
echo
"A string $caso_de_teste não consiste inteiramente de dígitos.\n";
}
}
?>

O exemplo acima produzirá:

A string 1820.20 não consiste inteiramente de dígitos.
A string 10002 consiste inteiramente de dígitos.
A string wsl!12 não consiste inteiramente de dígitos.

Exemplo #2 Um exemplo de ctype_digit() comparando strings com inteiros

<?php

$string_numerica
= '42';
$inteiro = 42;

ctype_digit($string_numerica); // verdadeiro
ctype_digit($inteiro); // false (código ASCII 42 é o caractere *)

is_numeric($string_numerica); // verdadeiro
is_numeric($inteiro); // verdadeiro
?>

Veja Também

  • ctype_alnum() - Verifica se os caracteres são alfanuméricos
  • ctype_xdigit() - Verifica se os caracteres representam um dígito hexadecimal
  • is_numeric() - Verifica se uma variável é um número ou uma string numérica
  • is_int() - Informa se o tipo de uma variável é um inteiro
  • is_string() - Verifica se o tipo de uma variável é string
  • IntlChar::isdigit() - Verifica se um ponto de código é um caractere de dígito

add a note add a note

User Contributed Notes 14 notes

up
56
info at directwebsolutions dot nl
12 years ago
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;
        }
    }
?>
up
14
Peter de Pijd
15 years ago
Note that an empty string is also false:
ctype_digit("") // false
up
8
smicheal2 at gmail dot com
9 years ago
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.
up
16
error17191 at gmail dot com
9 years ago
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
up
12
rlerne at gmail dot com
11 years ago
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.
up
11
strrev xc tod noxeh ta ellij
15 years ago
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)
up
14
a_p_leeming at hotmail dot com
15 years ago
Also note that

<?php ctype_digit("-1");   //false ?>
up
3
mdsky at web dot de
14 years ago
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.
up
2
John Saman
14 years ago
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.
up
-5
Skippy
13 years ago
If you need to check for integers instead of just digits you can supply your own function such as this:

<?php
function ctype_int($text)
{
    return
preg_match('/^-?[0-9]+$/', (string)$text) ? true : false;
}
?>
up
-3
zorrosNOSPAMwordsman at NOSPAM dot gmail dot com
8 years ago
If you want to verify whether or not a variable contains only digits, you can type cast it to a string and back to int and see if the result is identical. Like so:

<?php

// (bool) TRUE if only digits, FALSE otherwise
$isOnlyDigits = (string) (int) $input === (string) $input;

?>

I haven't benchmarked it, but I'm guessing it's significantly faster then regular expressions.
up
-5
raul dot 3k at gmail dot com
15 years ago
The ctype_digit can be used in a simple form to validate a field:
<?php
$field
= $_POST["field"];
if(!
ctype_digit($field)){
  echo
"It's not a digit";
}
?>

Note:
Digits is 0-9
up
-3
brcontainer at yahoo dot com dot br
6 years ago
ctype_digit don't support negative value in string:

<?php
var_dump
( ctype_digit('-10') ); //return bool(false)
?>

Improved (and simplified) Tim Boormans code:

<?php
/**
* Check input for existing only of digits (numbers)
* @author Guilherme Nascimento <brcontainer@yahoo.com.br>
* @param $digit
* @return bool
*/
function is_digit($digit)
{
    return
preg_match('#^-?\d+$#', $digit) && is_int((int) $digit);
}
up
-3
divinity76 at gmail dot com
3 years ago
an alternative if you want to check if it's a valid integer:

<?php
if(false!==filter_var($v, FILTER_VALIDATE_INT)){
   
// it's a valid int!
   
$v=(int)$v;
}else{
   
// it's not a valid int
}
?>

or if you want to check that it's a positive integer (>= 0):
<?php
if(false!==filter_var($v, FILTER_VALIDATE_INT, ["options"=>["min_range"=>0]])){
   
// it's a valid positive integer!
   
$v = (int)$v;
}else{
   
// it's not a valid positive integer
}

?>
To Top