PHP | ctype_digit() (Checks for numeric value)
Last Updated :
05 Jun, 2018
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:
- Gives Expected result when passing string not gives desired output when passing an integer.
- 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
$string = '123456789' ;
if ( ctype_digit( $string )) {
echo "Yes\n" ;
} else {
echo "No\n" ;
}
?>
|
Program: 2
Drive a code ctype_digit() function where input will be array of string which contains special characters, integers, strings.
<?php
$strings = array (
'Geeks-2018' ,
'geek@yahoo.com' ,
'10.99999Fe' ,
'12345' ,
'geeksforgeeks.org'
);
foreach ( $strings as $testcase ) {
if (ctype_digit( $testcase )) {
echo "Yes\n" ;
} else {
echo "No\n" ;
}
}
?>
|
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
$x = "-123" ;
if (ctype_digit( $x ))
echo "Yes\n" ;
else
echo "No\n" ;
$x = -123;
if ( is_int ( $x ))
echo "Yes" ;
else
echo "No" ;
?>
|
References :http://php.net/manual/en/function.ctype-digit.php
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...