Understanding the is_numeric()
Function in PHP (With Examples)
When developing websites and applications with PHP, validating user input or data types is essential. One commonly used function for checking if a value is a number or numeric string is the is_numeric()
function. In this article, we'll explore what is_numeric()
does, how to use it with examples, and why it is important.
What is is_numeric()
in PHP?
The is_numeric()
function in PHP is used to determine whether a variable is a number or a numeric string.
It returns:
TRUE
if the value is a number or a numeric stringFALSE
otherwise
Syntax:
is_numeric(mixed $value): bool
Parameter:
$value
— The variable you want to check.
Return Type:
- Boolean (
true
orfalse
)
Why Use is_numeric()
?
In PHP development, ensuring that user input or function parameters are numeric can prevent errors and ensure your application runs smoothly. Common use cases include:
- Validating form inputs
- Performing mathematical operations
- Ensuring database integrity
PHP is_numeric()
Function Examples
Example 1: Checking an Integer
$value = 123;
if (is_numeric($value)) {
echo "$value is numeric.";
} else {
echo "$value is not numeric.";
}
// Output: 123 is numeric.
Example 2: Checking a Numeric String
$value = "456";
if (is_numeric($value)) {
echo "$value is numeric.";
} else {
echo "$value is not numeric.";
}
// Output: 456 is numeric.
Example 3: Checking a Float
$value = 78.90;
if (is_numeric($value)) {
echo "$value is numeric.";
} else {
echo "$value is not numeric.";
}
// Output: 78.9 is numeric.
Example 4: Checking a Non-numeric String
$value = "Hello123";
if (is_numeric($value)) {
echo "$value is numeric.";
} else {
echo "$value is not numeric.";
}
// Output: Hello123 is not numeric.
Example 5: Checking Negative and Scientific Notation Numbers
$value1 = -123;
$value2 = "5e3"; // 5 x 10³ = 5000
echo is_numeric($value1) ? "$value1 is numeric.\n" : "$value1 is not numeric.\n";
echo is_numeric($value2) ? "$value2 is numeric.\n" : "$value2 is not numeric.\n";
// Output:
// -123 is numeric.
// 5e3 is numeric.
Important Notes about is_numeric()
- It accepts numbers in integer, float, scientific notation, and numeric strings.
- An empty string, null, or a non-numeric string will return
false
. - Even strings like
"0"
or"0.0"
are considered numeric.
Common Mistakes to Avoid
- Do not confuse
is_numeric()
withis_int()
oris_float()
.is_numeric()
checks for both numbers and strings that look like numbers. - If you need to check strictly for an integer or float (not a string), use
is_int()
oris_float()
instead.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.