Validating Numbers (and Other Data Types)
To find out whether any data is a number (or can be converted into a number), PHP offers several possibilities. First, the following helper functions check the data type of a variable:
-
is_array() Checks for array
-
is_bool() Checks for Boolean
-
is_float() Checks for float
-
is_int() Checks for integer
-
is_null() Checks for null
-
is_numeric() Checks for integers and floats
-
is_object() Checks for object
-
is_string() Checks for string
It is to be noted, however, that the numeric functionsis_float(), is_int(), and is_numeric()also try to convert the data from their original type to the numeric type.
Another approach to convert data types is something borrowed from Java and other strongly typed C-style languages. Prefix the variable or expression with the desired data type in parentheses:
$numericVar = (int)$originalVar;
In this case, however, PHP really tries to convert at any cost. Therefore, (int)'3DoorsDown' returns 3, whereas is_numeric('3DoorsDown') returns false. On the other hand, (int)'ThreeDoorsDown' returns 0.
Generally, is_numeric() (and is_int()/is_float()) seems to be the better alternative, whereas (int) returns an integer value even for illegal input. So, it's really a matter of the specific application at hand which method to choose.
The following code offers the best of both worlds. A given input is checked whether it is numeric with is_numeric(), and if so, it is converted into an integer using (int). Adaptions to support other (numeric) data types are trivial.
Generating Integer Values (check.inc.php; excerpt)
function getIntValue($s) {
if (!is_numeric($s)) {
return false;
} else {
return (int)$s;
}
}
|