Google News
logo
PHP Program to Check if a variable is numeric
In PHP, you can use the `is_numeric()` function to check if a variable is numeric.

Here's an example :
Program :
<?php
$var1 = 123;
$var2 = "456";
$var3 = "abc";

if (is_numeric($var1)) {
    echo "$var1 is numeric.<br>";
} else {
    echo "$var1 is not numeric.<br>";
}

if (is_numeric($var2)) {
    echo "$var2 is numeric.<br>";
} else {
    echo "$var2 is not numeric.<br>";
}

if (is_numeric($var3)) {
    echo "$var3 is numeric.<br>";
} else {
    echo "$var3 is not numeric.<br>";
}
?>
Output :
123 is numeric.
456 is numeric.
abc is not numeric.
In this example, the variables `$var1`, `$var2`, and `$var3` are assigned the values `123`, `"456"`, and `"abc"`, respectively. The `is_numeric()` function is used to check if each variable is numeric.

The first `if` statement checks if `$var1` is numeric. Since `$var1` is assigned a numeric value, the message "123 is numeric" will be printed.

The second `if` statement checks if `$var2` is numeric. Even though `$var2` is assigned a string value, it can be parsed as a numeric value, so the message "456 is numeric" will be printed.

The third `if` statement checks if `$var3` is numeric. Since `$var3` is assigned a string value that cannot be parsed as a numeric value, the message "abc is not numeric" will be printed.