Check if String is a Number in PHP

This tutorial will discuss about unique ways to check if string is a number in php.

Table Of Contents

Method 1: Using is_numeric()

To check if a string contains a number only, we can use the is_numeric() function. By number, we means that it can be an integer or a double value.

The is_numeric() function accepts a string as an argument and returns true if the value is a number or a numeric string, otherwise it returns false.

So we can pass over string into the is_numeric() function, and if it returns true then it means the given string is a number.

Let’s see the complete example,

<?php
$strValue = "11.45";

// Check if string is numeric
if (is_numeric($strValue)) {
    echo "The string represents a number.";
} else {
    echo "The string does not represent a number.";
}
?>

Output

The string represents a number.

Method 2: Using Regex

In this solution we can use the preg_match() function of PHP.

It accepts a regex pattern as the first argument and string as a second argument. It returns 1, if the given string matches the given regex pattern.

To check if stream is an integer only we can use this regex pattern -> ‘/^-?\d+(?:.\d+)?$/’.

In this regex patterns we are saying that first character can be a - symbol, after that it will have certain numbers, then optional dot and then again numbers only. Basically this regex pattern will match either integer or a double value. So if the string matches regex pattern, then it means string is a number.

Let’s see the complete example,

<?php
$strValue = "11.45";

// Check if string is numeric
if (preg_match('/^-?\d+(?:\.\d+)?$/', $strValue) === 1) {
    echo "The string represents a number.";
} else {
    echo "The string does not represent a number.";
}
?>

Output

The string represents a number.

Summary

We learned about two ways to check if a string is a number in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top