Check if String Contains only Numbers in PHP

This tutorial will discuss how to check if string contains only numbers in PHP.

To check if a string contains only numbers in PHP, we can use the ctype_digit() function.

The ctype_digit() function accepts a string as an argument and returns true if all the characters in the string are numerical. If there is at least one non-numeric character, it will return false.

In the below example, we will use this ctype_digit() to check if string “97856” contains a numeric value or not.

Let’s see the complete example,

<?php
$strValue = '97856';

// Check if string contains only digits
if (ctype_digit($strValue)) {
    echo "The string contains only numbers.";
} else {
    echo "The string contains non-numeric characters.";
}
?>

Output

The string contains only numbers.

Summary

Today, we learned how to check if string contains only numbers 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