Open In App

How to check if string contains only numeric digits in PHP ?

Last Updated : 04 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string, the task is to check whether the string contains only numeric digits in PHP. It is a common task to verify whether a given string consists of only numeric digits in PHP. It can be useful when dealing with user input validation, form submissions, or data processing tasks where numeric values are expected.

For instance, the below examples illustrate the concept:

Input: str = "1234"
Output: true

Input: str = "GeeksforGeeks2020" 
Output: false 

Here, we will cover three common scenarios for checking if the string contains only numeric digits.

Using ctype_digit Function

PHP provides a built-in function called ctype_digit() that can be used to check if all characters in a string are numeric digits.

Example: This example illustrates checking if string contains only numeric digits using ctype_digit Function in PHP.

PHP




<?php
  
function isNumeric($str)
{
    return ctype_digit($str);
}
  
// Driver code
$str1 = "12345";
$str2 = "gfg123";
  
echo isNumeric($str1) ? "Numeric String" : "Non Numeric String";
echo "\n";
echo isNumeric($str2) ? "Numeric String" : "Non Numeric String";
?>


Output

Numeric String
Non Numeric String

Using Regular Expressions

Regular expressions provide a powerful way to validate and manipulate strings. The preg_match() function can be used to check if a string contains only numeric digits.

Example: This example illustrates checking if string contains only numeric digits using the Regular Expressions.

PHP




<?php
  
function isNumeric($str)
{
    return preg_match('/^[0-9]+$/', $str);
}
  
// Driver code
$str1 = "12345";
$str2 = "abc123";
  
echo isNumeric($str1) ? "Numeric String" : "Non Numeric String";
echo "\n";
echo isNumeric($str2) ? "Numeric String" : "Non Numeric String";
  
?>


Output

Numeric String
Non Numeric String

Using is_numeric Function

The is_numeric() function in PHP checks if a variable is a numeric value or a numeric string.

Example: This example illustrates checking if string contains only numeric digits using the is_numeric Function.

PHP




<?php
  
function isNumeric($str)
{
    return is_numeric($str);
}
  
// Driver code
$str1 = "12345";
$str2 = "abc123";
  
echo isNumeric($str1) ? "Numeric String" : "Non Numeric String";
echo "\n";
echo isNumeric($str2) ? "Numeric String" : "Non Numeric String";
?>


Output

Numeric String
Non Numeric String


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads