To check if a variable is a number and is numeric in php, the easiest way is to use the php is_numeric() function.
if (is_numeric("31")) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric(1.3)) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric("php")) { echo "True"; } else { echo "False"; } // Output: False
The php is_numeric function allows us to check if a variable is a number and if a string is numeric or not.
If a variable has type integer or type float, the is_numeric() function will return true.
if (is_numeric(31)) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric(1.3)) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric(-100)) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric(-1.43)) { echo "True"; } else { echo "False"; } // Output: True
How to Check if String is Numeric with is_numeric in php
We can check if a string is numeric with the php is_numeric(). A string can be numeric if:
- the string contains only digits (0,1,2,3,4,5,6,7,8,9)
- the string has a + or – sign in front of the digits
- the string has a decimal place
- the string is a number expressed in scientific notation with an exponential
For example, the string “+34.12e10” is numeric since it is a number expressed in scientific notation.
Here are a few examples of checking to see if a string is numeric in php:
if (is_numeric("31")) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric("1.3")) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric("-100")) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric("1e6")) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric("+34.12e10")) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric("-32.0e2")) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric("+1")) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric("-.12")) { echo "True"; } else { echo "False"; } // Output: True
if (is_numeric("programming")) { echo "True"; } else { echo "False"; } // Output: False
if (is_numeric("12f")) { echo "True"; } else { echo "False"; } // Output: False
Hopefully this article has been beneficial for you to understand hwo to check if a variable is a number and if a string is numeric using php.