Check if String is an integer in PHP

This tutorial will discuss about a unique way to check if string is an integer in php.

PHP provides a function preg_match(), which accepts a regex pattern as the first argument and string as the second argument. It returns 1, if the string matches the given regex pattern.

Now, to check if string contains an integer only, we can use this regex pattern “/^-?\d+$/'”. It says that strings can start either with a - symbol or not, but after that it can have digits only from start to end.

So, if the preg_match() function returns 1, then it means the string contains an integer only. We have created a separate function for this,

function isStringInteger($str)
{
    return preg_match('/^-?\d+$/', $str) === 1;
}

It accepts a string is an argument and returns true if the string is an integer. In the below example we will use this function to check if string represent integer.

Let’s see the complete example,

<?php
/**
 * Checks if a string represents an integer using
 * regular expressions (preg_match()).
 *
 * @param string $str The string to check.
 * @return bool True if the string represents an integer, false otherwise.
 */
function isStringInteger($str)
{
    return preg_match('/^-?\d+$/', $str) === 1;
}

$strValue = "125";

if (isStringInteger($strValue)) {
    echo "The string contains an integer only";
} else {
    echo "The string does not represent an integer.";
}
?>

Output

The string contains an integer only

Summary

We learned how to Check if String is an integer 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