Tuesday, November 19, 2024
Google search engine
HomeLanguagesPHP | ctype_digit() (Checks for numeric value)

PHP | ctype_digit() (Checks for numeric value)

A ctype_digit() function in PHP used to check each and every character of text are numeric or not. It returns TRUE if all characters of the string are numeric otherwise return FALSE.

Syntax :

ctype_digit(string text)

Parameter Used:
The ctype_digit() function in PHP accepts only one parameter.

  • text : Its mandatory parameter which specifies the tested string.

Return Values:
It returns TRUE if all characters of the string are numeric otherwise return FALSE.

Errors and Exceptions:

  1. Gives Expected result when passing string not gives desired output when passing an integer.
  2. The function returns true on empty string previous versions of PHP 5.1.0

Examples:

Input  :789495001
Output : Yes
Explanation : All digits, return True

Input  : 789.0877
Output : No
Explanation: String contains floating point, 
return false.                   

Below programs illustrate the ctype_digit() function.

Program: 1 Checking ctype_digit() function for a single string which contains all digits.




<?php
// PHP program to check given string is 
// control character
  
$string = '123456789';
  
    
    // Checking above given string 
    // by using of ctype_digit() function.
    if ( ctype_digit($string)) {
          
        // if true then return Yes
        echo "Yes\n";
    } else {
          
        // if False then return No
        echo "No\n";
    }
  
?>


Output:

Yes

Program: 2
Drive a code ctype_digit() function where input will be array of string which contains special characters, integers, strings.




<?php
// PHP program to check is given string
// contains all digits using ctype_digit
  
  
$strings = array(
    'Geeks-2018',
    'geek@yahoo.com',
    '10.99999Fe',
    '12345',
    'geeksforgeeks.org'
);
  
// Checking above given strings 
//by used of ctype_digit() function .
  
foreach ($strings as $testcase) {
      
    if (ctype_digit($testcase)) {
        // if true then return Yes
        echo "Yes\n";
    } else {
        // if False then return No
        echo "No\n";
    }
}
  
?>


Output:

No
No
No
Yes
No

ctype_digit() vs is_int()
ctype_digit() is basically for string type and is_int() for integer types. ctype_digit() traverses through all characters and checks if every character is digit or not. For example,




<?php
// PHP code to demonstrate difference between
// ctype_digit() and is_int().
$x = "-123";
if (ctype_digit($x))
   echo "Yes\n";
else 
   echo "No\n";
  
$x = -123;
if (is_int($x))
   echo "Yes";
else 
   echo "No";
?>


Output:

No
Yes

References :http://php.net/manual/en/function.ctype-digit.php

Previous article
Next article
RELATED ARTICLES

Most Popular

Recent Comments