is_numeric()
19th January 2021
0 Comments
Programming Language
PHP [Versions: 4, 5, 7, 8]
Syntax
Typical Usage
Checks a given PHP variable to determine whether or not it is numeric.
Accepted Parameters
- value (mixed) (Required): The value you’d like to check.
Return Value(s)
Returns to true if the value is numeric and false if not.Examples of is_numeric()
Example 1
<?php
$num = 1;
if ( is_numeric($num) ) {
echo $num . ' is a number!';
}
else {
echo $num . ' is not a number. Shame!';
}
The above will output “1 is a number!” because $var is the number 1.
Example 2
<?php
$string = '1234';
if ( is_numeric($string) ) {
echo $string. ' is a number!';
}
else {
echo $string . ' is not a number. Shame!';
}
The above will output “1234 is a number!”. Although 1234 is a string, it is a numeric string and is_numeric() evaluates it to true.
Example 3: is_numeric() with Dashes and Underscores.
<?php
$string = '1-2';
if ( is_numeric($string) ) {
echo $string. ' is a number!';
}
else {
echo $string . ' is not a number. Shame!';
}
The above will output “1-2 is not a number. Shame!”. Underscores and commas will also produce a false result.
Example 4: is_numeric() with Periods
<?php
$float = '52.2565';
if ( is_numeric($float) ) {
echo $float. ' is a number!';
}
else {
echo $float. ' is not a number. Shame!';
}
The above will output “52.2565 is a number!”. Floats are decimal numbers and evaluate to true. More than one period will cause is_numeric() to return false.
Was This Helpful?
If this post has helped you, please let me know. Your feedback will be highly appreciated and will help me build better content.