One of the great features of PHP is its automatic typecasting of variables. You don’t need to tell PHP whether you are storing a string, a float or an integer value. This gives rise to some interesting error checking scenarios though. One of the simplest, is checking whether the value submitted from a form is numeric or not.
Annoyingly, every value submitted from a form is classed as a string in PHP. That doesn’t stop you performing calculations on the submitted value as if it were a number, but it does mean that is_integer() will always return false for that value. The PHP manual advises us to use is_numeric() instead, however is_numeric() and is_integer() are very different. For example, is_numeric() is quite happy to accept any valid number, which can include minus values, floating points and exponential numbers. For error checking this can be pretty worthless. Let’s look at a couple of different scenarios:
Scenario 1: we are passing a database ID in a hidden INPUT tag, and we want to ensure that only a valid integer ends up in the subsequent database query.
We can actually typecast the variable as follows:
$id = (int)$_POST['id'];
or
$id = intval($_POST['id']);
Nice and simple. However, minus values can also be valid integers, and sometimes we don’t want those either. We could run two tests, but that’s not particularly elegant. So…
Scenario 2: we are passing a monetary value to a payment gateway and it has to be in the lowest currency denominater (e.g. £10.53 becomes 1053). In this scenario, floating points, minus symbols and exponentials are all unacceptable.
The simple answer is regular expressions (regex) using preg_match.
if(!preg_match("/^[0-9]+$/", $_POST['amount']) {
// not valid
} else {
// valid
}

Recent Comments