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;
}
}
?>
ctype_digit
(PHP 4 >= 4.0.4, PHP 5)
ctype_digit — Vérifie qu'une chaîne est un entier
Description
$text
)
ctype_digit() vérifie si tous les caractères
de la chaîne text sont des chiffres.
Liste de paramètres
-
text -
La chaîne testée.
Valeurs de retour
Retourne TRUE si tous les caractères de text sont
des entiers, FALSE sinon.
Historique
| Version | Description |
|---|---|
| 5.1.0 |
Avant PHP 5.1.0, cette fonction retournait TRUE
lorsque le paramètre text était une chaîne vide.
|
Exemples
Exemple #1 Exemple avec ctype_digit()
<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
if (ctype_digit($testcase)) {
echo "La chaîne $testcase ne contient que des entiers.\n";
} else {
echo "La chaîne $testcase ne contient pas que des entiers.\n";
}
}
?>
L'exemple ci-dessus va afficher :
La chaîne 1820.20 ne contient pas que des entiers. La chaîne 10002 ne contient que des entiers. La chaîne wsl!12 ne contient pas que des entiers.
Exemple #2 Exemple avec ctype_digit() pour comparer des chaînes et des nombres
<?php
$numeric_string = '42';
$integer = 42;
ctype_digit($numeric_string); // true
ctype_digit($integer); // false (ASCII 42 correspond au caractère *)
is_numeric($numeric_string); // true
is_numeric($integer); // true
?>
Notes
Note:
Cette fonction attend une chaîne afin d'être pertinente ; par exemple, le fait de passer un entier ne retournera pas le résultat attendu. Voir aussi la section sur les types de ce manuel.
Note:
Si un entier dans l'intervalle -128 et 255 inclus est fourni, il sera interprété comme la valeur ASCII d'un seul caractère (les valeurs négatives se verront ajouter 256 afin d'autoriser les caractères dans l'intervalle ASCII étendue). Tout autre entier sera interprété comme une chaîne de caractères contenant les décimales de l'entier.
Voir aussi
- ctype_alnum() - Vérifie qu'une chaîne est alphanumérique
- ctype_xdigit() - Vérifie qu'un caractère représente un nombre hexadécimal
- is_numeric() - Détermine si une variable est un type numérique
- is_int() - Détermine si une variable est de type nombre entier
- is_string() - Détermine si une variable est de type chaîne de caractères
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.
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)
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;
}
?>
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
Before anyone uses this code I suggest they check it against known valid IMEIs - I did and it failed half of mine.
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.
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.
Remove all non-printable characters from a string:
<?php
$str = implode('', array_filter(str_split($str, 1), 'ctype_print'));
?>
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);
}
?>
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;
}
?>
