The easiest way to check if a string is a number is by using is_numeric in PHP. The function is_numeric is a simple and straightforward way of determining if the string is a number. By using the is_numeric function in your web application you'll be able to use PHP to check if a variable and input data is a number. Let's break down the function, and find out how it works, along with easy-to-follow PHP code examples all written by our in-house team of PHP experts.
PHP is_numeric Function
Checking if a string is a number has never been simpler when using the is_numeric PHP function. It works by passing a variable to the function and it will return a boolean dependent on that variable's value. If the boolean returns as true, is it a number, otherwise false, it's not.
The function, is_numeric takes a single parameter, which can be of mixed types, typically, strings, integers, or variables, and will return a boolean, true or false. The "$value" parameter is required, and without triggers a "ArgumentCountError: is_numeric() expects exactly 1 argument", 0 given" fatal error!
is_numeric(mixed $value): bool
As a PHP programmer, this can be really useful when working with input data when you need to check that the data you're working with is a number. Let's explore it in action.
echo is_numeric(2468);
# Outputs
true
When using is_numeric, it's important to remember that PHP will attempt to convert variables passed to it into numbers. That means when passing a string that has a numeric value, it will, in fact, pass the is_numeric check, even though, it's technically a string and not a raw number value. We're using var_dump here to print to screen what is contained in the variable "$string".
$string = (string) '123';
var_dump(is_numeric($string));
# Outputs
int(123)
That's also the same if numbers start with a zero, are floats (simply put a number with decimals), and even the hexadecimal equivalent of the number. Let's explore all of those below.
# Float is numeric
var_dump(is_numeric(02468));
# Hexadecimal equivalent
var_dump(is_numeric(0x9A4));
# All the above output
int(2468)
var_dump(is_numeric(24.68));
# Outputs
int(24.68)
Converting a String to a Number
When using the numeric function and it returns false, that means the passing value is not a number, that's particularly true when the value is a string and contains non-numeric characters. In other words, anything that isn't a number, a period dot, or a number prefix with "0b" binary or "0x" hexadecimal. If your application requires the value to be an integer, maybe to be stored in a particular way or converted into something, like a date, you can convert the string to a number by stripping out non-numeric characters by using type casting. The below example is one way you could attempt this. It works by putting the type in brackets before the variable "(int)", which PHP will convert for you. You'll see the original value of the variable "foo" was a string, but once typecast, it's now an int.
$foo = '123';
var_dump($foo);
# Outputs
string(3) "123"
var_dump((int) $foo);
# Outputs
int(123)
Whitespace in is_numeric PHP function
When passing numbers to the is_numeric function to check strings are numbers, a common case for this is checking user-inputted data. That might be, grabbing the ID from the URL from inside your web application. You might have an edit screen, such as "/edit/42", where 42 is the ID of the item the user wishes to edit. It's always important never to simply trust input data from users, because it might be incorrect. Whitespace is one example of this, would your web application still behave correctly if the URL had a space at the end such as "/edit/1 "? Prior to PHP 8, this could trigger a false boolean, however, in PHP version 8, now produces a true boolean.
NotANumber (NAN) and is_numeric
PHP follows many computing standards, including the IEEE 754 standard. This standard specifies that floating-point numbers can have special values like NAN to represent undefined or unrepresentable results of arithmetic operations. Whilst NAN isn't conventional it is still worth noting that passing NAN to PHP's is_numeric will in fact return a boolean true.
Checking if the array key is a number
Another example of is_numeric in action is how to check that a given array key is a number. Take a real-world example, that could be from a shopping basket that uses inputted data from the user to determine the quantity of an item. Let's explore a simple example of how this might work and why it would be very useful to check if the inputted data from a user was passed through is_numeric.
Here we are changing the total price based on the quantity provided by the user. By default, the item price is 5 and the quantity is 1. So the default price is 5. But if the quantity request was set, let's say it was 10, then the code will check if it is a number, if that's true then times the default item price by 10, the quantity. Whilst you shouldn't accept data directly from the user like this in our $_REQUEST section, in our hypothetical example, if we didn't check if the quantity variable was a number and then attempted to use it in this mathematical equation, we'd get an error. For example, if we as the user set the quantity to "foobar" without checking is_numeric on the string, we'd trigger a fatal error; "Uncaught TypeError: Unsupported operand types: int * string". Now for our application, that's pretty bad, and an even worse experience for our user. To avoid this fatal error potential, you can use an IF statement combined with the is_numeric function as seen below in this PHP code.
$total = 0;
$quantity = 1;
$itemPrice = 5;
$quantity = $_REQUEST['quantity'] ?? 1;
if (is_numeric($quantity)) {
$total = $itemPrice * $quantity;
}
echo $total;
Conclusion
Using the is_numeric function in PHP is a popular choice throughout the open-source PHP community and web application projects you are likely to work on as a PHP programmer, whether that's for your job or personal hobby. Is_numeric is a powerful, versatile yet simple way to ensure that you;
- Validate user input
- Enhance your data integrity
- Prevention of errors