note 87113 deleted from function.ctype-digit by salathe
| From: | salathe@php.net | Date: | Fri, 06 Feb 2015 12:59:33 +0000 |
| Subject: | note 87113 deleted from function.ctype-digit by salathe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-201606@lists.php.net to get a copy of this message | ||
Note Submitter: Anonymous
----
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);
}
?>