PHP is_numeric() - Check Numeric
The is_numeric() function in PHP is an essential tool to validate variables as numbers. Whether you are working with forms, API inputs, or database values, determining if a variable is numeric is a common requirement. This tutorial guides you through using the is_numeric() function effectively for variable handling in PHP.
Prerequisites
- Basic understanding of PHP syntax and variables
- PHP installed on your system (PHP 5.0 or higher recommended)
- A code editor or IDE to write PHP scripts
Setup Steps
- Install PHP if not already installed. You can download it from php.net.
- Create a PHP file, e.g.,
is_numeric_example.php. - Open the file in your editor and prepare to implement
is_numeric()test cases.
Understanding PHP is_numeric() Function
The syntax of is_numeric() is simple:
bool is_numeric(mixed $var)
It accepts any variable as input and returns true if the variable is a number or a numeric string, else false.
What counts as numeric?
- Integer numbers (e.g., 100, -50)
- Floating-point numbers (e.g., 10.5, -3.14)
- Numeric strings (e.g., "1234", "-12.34")
- Scientific notation strings (e.g., "1.2e3")
What is NOT numeric?
- Strings with non-numeric characters (e.g., "12a34")
- Boolean values like true or false
- Null values
- Arrays or objects
Examples of Using is_numeric()
Example 1: Checking integers and floats
<?php
$var1 = 123;
$var2 = 4.56;
if (is_numeric($var1)) {
echo "$var1 is numeric.\n";
} else {
echo "$var1 is not numeric.\n";
}
if (is_numeric($var2)) {
echo "$var2 is numeric.\n";
} else {
echo "$var2 is not numeric.\n";
}
?>
Output:
123 is numeric.
4.56 is numeric.
Example 2: Checking numeric strings and non-numeric strings
<?php
$var1 = "567";
$var2 = "hello123";
$var3 = "1.23e5";
echo is_numeric($var1) ? "True\n" : "False\n"; // True
echo is_numeric($var2) ? "True\n" : "False\n"; // False
echo is_numeric($var3) ? "True\n" : "False\n"; // True
?>
Example 3: Edge cases with boolean, null, and arrays
<?php
$var1 = true;
$var2 = null;
$var3 = array(1, 2, 3);
echo is_numeric($var1) ? "True\n" : "False\n"; // False
echo is_numeric($var2) ? "True\n" : "False\n"; // False
echo is_numeric($var3) ? "True\n" : "False\n"; // False
?>
Best Practices for Using is_numeric()
- Use
is_numeric()to validate form inputs before further processing or type casting. - Combine
is_numeric()with strict type checks (likeis_int()oris_float()) if you want to differentiate between numeric strings and actual number types. - Remember that
is_numeric()accepts numeric strings, so always sanitize inputs when security is a concern. - Use
filter_var()for more complex validations but rely onis_numeric()for simple numeric checks.
Common Mistakes to Avoid
- Assuming a numeric string is the same as an integer type —
'123'is numeric but still a string. - Using
is_numeric()to validate currency or formatted numbers with commas (like1,000) which are considered non-numeric. - Confusing
is_numeric()withis_int()oris_float()— these check variable types, not just the content. - Passing arrays, objects, or resources to
is_numeric(), expecting a numeric result.
Interview Questions
Junior-level Questions
- Q1: What does the
is_numeric()function do in PHP?
A: It checks whether a variable is a number or a numeric string and returns true or false accordingly. - Q2: Will
is_numeric("123")return true or false?
A: True, because "123" is a numeric string. - Q3: Does
is_numeric()accept variables of any type?
A: Yes, it accepts variables of any type but only returns true for numbers and numeric strings. - Q4: Is
is_numeric(3.5)true or false?
A: True, because 3.5 is a float and numeric. - Q5: Does
is_numeric()recognize scientific notation like"1e4"?
A: Yes, it returns true for valid scientific notation strings.
Mid-level Questions
- Q1: What will
is_numeric("10,000")return and why?
A: False, because the string contains a comma which makes it non-numeric. - Q2: How to differentiate between a numeric string and an actual number if both pass
is_numeric()test?
A: Useis_int()oris_float()to check the type in addition tois_numeric(). - Q3: Can
is_numeric()be used to validate currency values? Why or why not?
A: Generally no, because currency formats often include commas, symbols, or spaces that make them non-numeric strings. - Q4: What is the difference in behavior between
is_numeric()andctype_digit()?
A:ctype_digit()checks if all characters are digits (no decimal points or negative signs) whileis_numeric()allows floats and negatives. - Q5: How does
is_numeric()behave with boolean values?
A: It returns false for booleans because they are not considered numeric.
Senior-level Questions
- Q1: Explain why
is_numeric()returns true for a string containing scientific notation.
A: Because the function accepts strings representing numbers including integers, floats, and numbers in scientific notation as valid numeric values. - Q2: In which scenarios would relying solely on
is_numeric()be unsafe or insufficient?
A: When strict type checking is required, or when input sanitization for security is necessary to prevent injection attacks. - Q3: How does PHP internally determine if a variable is numeric in
is_numeric()?
A: PHP tries to parse the variable as an integer or float and returns true if this parsing succeeds without remaining invalid characters. - Q4: Can
is_numeric()distinguish localized numeric formats? For example, "12,34.56".
A: No,is_numeric()only recognizes standard numeric formats without thousands separators. - Q5: How can you extend
is_numeric()to validate complex numeric inputs such as hexadecimal or octal numbers?
A: You would need custom validation using regex or built-in functions likectype_xdigit()for hex or parsing functions with base specification, asis_numeric()does not support these by default.
FAQ
Q1: Does is_numeric() consider negative numbers as numeric?
Yes, negative numbers like -10 or "-4.5" are considered numeric and return true.
Q2: Is is_numeric() affected by locale settings?
No, it strictly checks for numbers using the standard English notation with dot as decimal separator.
Q3: Can is_numeric() validate numbers with spaces?
No, leading or trailing spaces will cause is_numeric() to return false.
Q4: Does is_numeric(null) return true?
No, null is not numeric and the function returns false.
Q5: How to convert a numeric string validated with is_numeric() into a number?
You can cast it using (int) or (float), or let PHP do implicit conversion during arithmetic operations.
Conclusion
The PHP is_numeric() function is a straightforward, reliable way to check if a variable holds a numeric value or a string representing a number, including floats and scientific notation. It is invaluable in variable handling scenarios such as form validation and data processing. Understanding its behavior, limitations, and how best to use it will elevate your PHP coding quality and input validation strategies.