This tutorial will discuss about a unique way to check if string is an integer in php.
To check if a string contains only an integer, we can use the is_numeric()
function in PHP. It accepts a variable as an argument and returns true, if the given variable is either numeric or a string containing numeric value. But if the variable is not set yet, then in that case it will still return true. So we need to use the ctype_digit()
function along with the is_numeric()
function.
The ctype_digit()
function accept a string as an argument, and returns true if the all the characters in the given string are digits.
So, we can use a combination of both the methods i.e. is_numeric($str) && ctype_digit($str)
, to check if given string is in valid integer or not.
For this, we have created a separate function i.e.
function isIntegerString($str) { return is_numeric($str) && ctype_digit($str); }
It accepts a string as an argument and returns true if the given string is a valid integer.
Let’s see the complete example,
Frequently Asked:
<?php /** * Checks if a string represents a valid integer * using is_numeric() and ctype_digit(). * * @param string $str The string to check. * @return bool True if the string represents a valid integer, false otherwise. */ function isIntegerString($str) { return is_numeric($str) && ctype_digit($str); } $strValue = "956"; // Check if string is a valid integer if (isIntegerString($strValue)) { echo "The string represents a valid integer."; } else { echo "The string does not represent a valid integer."; } ?>
Output
The string represents a valid integer.
Summary
We learned a way to check if a string contains an integer only in PHP.