ctype_digit

(PHP 4 >= 4.0.4, PHP 5)

ctype_digitChequear posibles caracteres numéricos

Descripción

bool ctype_digit ( string $text )

Verifica si todos los caracteres en la string entregada, text, son numéricos.

Parámetros

text

La cadena probada.

Valores devueltos

Devuelve TRUE si cada caracter del texto es un dígito decimal, o FALSE de lo contrario.

Historial de cambios

Versión Descripción
5.1.0 En versiones anteriores a PHP 5.1.0, esta función devolvía TRUE cuando text era una cadena vacía.

Ejemplos

Ejemplo #1 Un ejemplo de ctype_digit()

<?php
$cadenas 
= array('1820.20''10002''wsl!12');
foreach (
$cadenas as $caso_prueba) {
    if (
ctype_digit($caso_prueba)) {
        echo 
"La cadena $caso_prueba consiste completamente de dígitos.\n";
    } else {
        echo 
"La cadena $caso_prueba no consiste completamente de dígitos.\n";
    }
}
?>

El resultado del ejemplo sería:

La cadena 1820.20 no consiste completamente de dígitos.
La cadena 10002 consiste completamente de dígitos.
La cadena wsl!12 no consiste completamente de dígitos.

Ejemplo #2 Un ejemplo de ctype_digit() comparando strings con integers

<?php

$numeric_string 
'42';
$integer        42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 es el caracter *)

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

Notas

Nota:

Esta función espera un string para ser útil, por ejemplo si pasamos un integer no puede devolver el resultado esperado. Sin embargo, nótese también los formularios HTML resultarán en strings numéricos y no en integers. Ver también la sección del manual tipos.

Nota:

Si se proporciona un integer entre -128 y 255 inclusive, se interpreta como el valor ASCII de un simple caráter (a los valores negativos se le añade 256 para permitir caracteres en el rango ASCII Extendido). Cualquier otro entero se interpreta como una cadena que contiene los dígitos decimales del entero.

Ver también

  • ctype_alnum() - Chequear posibles caracteres alfanuméricos
  • ctype_xdigit() - Chequear posibles caracteres que representen un dígito hexadecimal
  • is_numeric() - Comprueba si una variable es un número o un string numérico
  • is_int() - Comprueba si el tipo de una variable es integer
  • is_string() - Comprueba si una variable es de tipo string

add a note add a note

User Contributed Notes 10 notes

up
16
info at directwebsolutions dot nl
2 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
7
rlerne at gmail dot com
1 year 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
6
John Saman
4 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
6
strrev xc tod noxeh ta ellij
4 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
7
a_p_leeming at hotmail dot com
5 years ago
Also note that

<?php ctype_digit("-1");   //false ?>
up
6
Peter de Pijd
5 years ago
Note that an empty string is also false:
ctype_digit("") // false
up
1
raul dot 3k at gmail dot com
5 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
0
Skippy
3 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
0
mdsky at web dot de
4 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
-12
Anonymous
6 years ago
Indeed, ctype_digit only functions correctly on strings. Cast your vars to string before you test them. Also, be wary and only use ctype_digit if you're sure your var contains either a string or int, as boolean true for ex will convert to int 1.

To be truly safe, you need to check the type of the var first. Here's a wrapper function that improves upon ctype_digit's broken implementation:

<?php

// replacement for ctype_digit, to properly
// handle (via return value false) nulls,
// booleans, objects, resources, etc.
function ctype_digit2 ($str) {
    return (
is_string($str) || is_int($str) || is_float($str)) &&
       
ctype_digit((string)$str);
}

?>

If, like me, you're not willing to take a chance on ctype_digit having other problems, use this version:

<?php

// replacement for ctype_digit, to properly
// handle (via return value false) nulls,
// booleans, objects, resources, etc.
function ctype_digit2 ($str) {
    return (
is_string($str) || is_int($str) || is_float($str)) &&
       
preg_match('/^\d+\z/', $str);
}

?>
To Top