note 108712 added to function.ctype-digit
| From: | info at directwebsolutions dot nl | Date: | Sat, 19 May 2012 21:16:21 +0000 |
| Subject: | note 108712 added to function.ctype-digit | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-188084@lists.php.net to get a copy of this message | ||
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;
}
}
?>
----
Server IP: 83.137.20.135
Probable Submitter: 84.26.9.163
----
Manual Page -- http://www.php.net/manual/en/function.ctype-digit.php
Edit -- https://master.php.net/note/edit/108712
Del: integrated -- https://master.php.net/note/delete/108712/integrated
Del: useless -- https://master.php.net/note/delete/108712/useless
Del: bad code -- https://master.php.net/note/delete/108712/bad+code
Del: spam -- https://master.php.net/note/delete/108712/spam
Del: non-english -- https://master.php.net/note/delete/108712/non-english
Del: in docs -- https://master.php.net/note/delete/108712/in+docs
Del: other reasons-- https://master.php.net/note/delete/108712
Reject -- https://master.php.net/note/reject/108712
Search -- https://master.php.net/manage/user-notes.php