PHP ctype_digit() function with example

PHP ctype_digit() work: Here, we will find out about the ctype_digit() work with the example in PHP.

PHP ctype_digit() work

ctype_digit() work is a character type (CType) work in PHP, it is utilized to check whether a given string contains just digits or not.

It returns genuine – if the string contains just digits (0…9), else it returns false.

Syntax:

    ctype_digit(string) : bool

Output:

    Input: "1234"
    Output: true
    Input: "Hello123"
    Output: false
    Input: "abc@123&a"
    Output: false

PHP Code:

<?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:

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.

Leave a Comment