OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Numbers In PHP

Code snippet for how to Check If A String Contains Only Numbers In PHP with sample and detail explanation

Managing and manipulating strings efficiently is a crucial aspect of programming. In this article, we’ll cover how you can check if a string contains only numbers in PHP.

Code snippet is_numeric() function

The is_numeric() function in PHP is used to validate if a variable is a number or a numeric string. Here is a simple code snippet that demonstrates this:

$str = "123456";
if(is_numeric($str)){
    echo "The string contains only numbers.";
}else{
    echo "The string does not contain only numbers.";
}

Code Explanation for is_numeric() function

Let’s break down the code explained above:

  1. $str = "123456"; Here, we are declaring a variable named $str and assigning a numeric string to it.

  2. if(is_numeric($str)){ We use the built-in PHP function is_numeric(), and inside the parenthesis, we pass the variable that we want to check.

  3. echo "The string contains only numbers.";} If the is_numeric() function returns true, this means that the $str variable only contains numbers. Thus, the string “The string contains only numbers.” is printed.

  4. else{ echo "The string does not contain only numbers."; } If the is_numeric() function returns false, meaning the $str variable contains characters other than numbers, the string “The string does not contain only numbers.” is printed.

This is a straightforward and simple way to check if a string in PHP only contains numbers. Always keep in mind that validating and verifying data is critical for improving your application’s reliability and preventing potential problems in future.

php