PHP ctype_digit() Function (With Examples)

In this tutorial, we will learn about the PHP ctype_digit() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP ctype_digit() function

The ctype_digit() function is a character type (CType) function in PHP, it is used to check whether a given string contains only digits or not.

Syntax

The syntax of the ctype_digit() function:

ctype_digit(string) : bool

Parameters

The parameters of the ctype_digit() function:

  • string: An input string.

Return Value

The return type of this method is bool, it returns true – if the string contains only digits (0...9), else it returns false.

Sample Input/Output

Input: "1234"
Output: true

Input: "Hello123"
Output: false

Input: "abc@123&a"
Output: false

PHP ctype_digit() Function Example

<?php
    $str = "123456";
    if(ctype_digit($str))
        echo ("$str contains only digits.\n");
    else
        echo ("$str does not contain only digits.\n");

    $str = "123.456";
    if(ctype_digit($str))
        echo ("$str contains only digits.\n");
    else
        echo ("$str does not contain only digits.\n");

    $str = "Hello world123";
    if(ctype_digit($str))
        echo ("$str contains only digits.\n");
    else
        echo ("$str does not contain only digits.\n");

    $str = "abc@123&a";
    if(ctype_digit($str))
        echo ("$str contains only digits.\n");
    else
        echo ("$str does not contain only digits.\n");
?>

Output

The output of the above example is:

123456 contains only digits.
123.456 does not contain only digits.
Hello world123 does not contain only digits.
abc@123&a does not contain only digits.

To understand the above example, you should have the basic knowledge of the following PHP topics:


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.