downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

ctype_graph> <ctype_cntrl
[edit] Last updated: Sat, 07 Jan 2012

view this page in

ctype_digit

(PHP 4 >= 4.0.4, PHP 5)

ctype_digitAuf Ziffern überprüfen

Beschreibung

bool ctype_digit ( string $text )

Prüft ob der übergebene String nur aus Ziffern besteht.

Parameter-Liste

text

Der zu prüfende String.

Rückgabewerte

Liefert TRUE wenn jedes Zeichen in text eine Ziffer ist, ansonsten FALSE.

Changelog

Version Beschreibung
5.1.0 Vor PHP 5.1.0 gab die Funktion auch TRUE zurück wenn der Eingabestring komplett leer war.

Beispiele

Beispiel #1 ctype_digit() Beispiel

<?php
$strings 
= array('1820.20''10002''wsl!12');
foreach (
$strings as $testcase) {
    if (
ctype_digit($testcase)) {
        echo 
"Der String $testcase besteht aus Ziffern.\n";
    } else {
        echo 
"Der String $testcase enthält nicht nur Ziffern.\n";
    }
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Der String 1820.20 enthält nicht nur Ziffern.
Der String 10002 besteht aus Ziffern.
Der String wsl!12 enthält nicht nur Ziffern.

Beispiel #2 A ctype_digit() example comparing strings with integers

<?php

$numeric_string 
'42';
$integer        42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false

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

Anmerkungen

Hinweis:

Diese Funktion ist nur sinnvoll wenn der Eingabeparameter ein string ist, ein integer Wert als Eingabe wird immer FALSE als Ergebnis liefern. Da auch numerische HTML-Formulareingaben immer als String übergeben werden hat die Funktion hier dennoch ihren Sinn. Siehe auch den types Abschnitt des Handbuchs.

Hinweis:

Wenn ein integer zwischen -128 und 255 (inklusive) übergeben wird, wird dieser als ASCII Wert eines einzelnen Buchstabens interpretiert (zu negativen Werten wird 256 dazu addiert, um Buchstaben des Erweiterten ASCII Zeichensatzes zu erlauben). Alle anderen Integer werden wie ein String interpretiert, welcher die dezimalen Ziffern des Integers enthält.

Siehe auch

  • ctype_alnum() - Auf alphanumerische Zeichen überprüfen
  • ctype_xdigit() - Auf Hexadezimalziffern überprüfen
  • is_numeric() - Prüft, ob eine Variable eine Zahl oder ein numerischer String ist
  • is_int() - Prüft, ob eine Variable vom Typ int ist
  • is_string() - Prüft, ob Variable vom Typ string ist



ctype_graph> <ctype_cntrl
[edit] Last updated: Sat, 07 Jan 2012
 
add a note add a note User Contributed Notes ctype_digit
Skippy 25-Oct-2011 03:44
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;
}
?>
portalpress dot org at gmail dot com 22-May-2011 10:24
To my surprise after one million iterations:

It took 0.5646638 seconds to false if(('abc'*1 . '')==='abc')
It took 0.5725240 seconds to true if(('123'*1 . '')==='123')
It took 0.3741021 seconds to false if((('abc'*1) . '')==='abc')
It took 0.4357590 seconds to true if((('123'*1) . '')==='123')
It took 0.3529291 seconds to false ctype_digit('abc')
It took 0.3391420 seconds to true ctype_digit('123')

The function ctype_digit() is faster then an inline if().
But this test also shows the value of ((first*1) . second).
mdsky at web dot de 21-May-2010 02:44
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.
John Saman 05-Feb-2010 06:38
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.
strrev xc tod noxeh ta ellij 14-Dec-2009 09:41
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)
walter 09-Dec-2009 03:18
I was looking at whether this would save time on the numerous input validations I make in legions of scripts.  Typically I use a function numbers_only() which simply does a preg_replace() to remove non-digits from a string.

To test for a possible speedup, I created a new function which only performed the preg_replace() once a type_digit() check had failed.

The results for 1 million interations showed that using ctype_digit() beforehand caused approximately 1/3rd additional latency on strings that were going to be preg_replace()'d anyway (ie: strings that did not contain only digits).  It caused an over 100% speedup over that (latency inclusive) time for input strings that were pure numbers.  The speedup was around 2/3 of the original blind preg_replace().

The lesson for me is that it's only worth trying to optimise away preg_replace() using ctype_digit() or similar if you know with some certainty that the vast majority of your inputs will lean one way or the other.

Having said that, ctype_digit() seems to be cosnistently 30% faster than preg_match().  But adding the additional PHP option as a requirement for your codebase may not justify the optimisation.

Let's face it: PHP aint exactly assembler, even if it is much faster than ruby :)
Chris 02-Aug-2009 02:17
Remove all non-printable characters from a string:
<?php
$str
= implode('', array_filter(str_split($str, 1), 'ctype_print'));
?>
Peter de Pijd 18-Jul-2009 05:53
Note that an empty string is also false:
ctype_digit("") // false
a_p_leeming at hotmail dot com 24-May-2009 08:17
Also note that

<?php ctype_digit("-1");   //false ?>
raul dot 3k at gmail dot com 09-Apr-2009 10:21
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
Anonymous 19-Nov-2008 02:56
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);
}

?>
minterior at gmail dot com 10-Sep-2007 09:43
I use ctype_digit() function as a part of this IMEI validation function.

<?php

/**
 * Check the IMEI of a mobile phone
 * @param $imei IMEI to validate
 */
function is_IMEI_valid($imei){   
    if(!
ctype_digit($imei)) return false;
   
$len = strlen($imei);
    if(
$len != 15) return false;

    for(
$ii=1, $sum=0 ; $ii < $len ; $ii++){
        if(
$ii % 2 == 0) $prod = 2;
        else
$prod = 1;
       
$num = $prod * $imei[$ii-1];
        if(
$num > 9){
         
$numstr = strval($num);
         
$sum += $numstr[0] + $numstr[1];
        }else
$sum += $num;
    }

   
$sumlast = intval(10*(($sum/10)-floor($sum/10))); //The last digit of $sum
   
$dif = (10-$sumlast);
   
$diflast = intval(10*(($dif/10)-floor($dif/10))); //The last digit of $dif
   
$CD = intval($imei[$len-1]); //check digit

   
if($diflast == $CD) return true;

    return
false;
}
?>

 
show source | credits | sitemap | contact | advertising | mirror sites