What is the ctype_alpha method in PHP?
The ctype_alpha method can be used to check if all the characters of the text are alphabetical.
The alphabet characters include both upper case
A-Zand lower casea-zcharacters.
Syntax
ctype_alpha(mixed $text): bool
Return value
This method returns a Boolean value.
Code
<?php$str = "abcABC";printIsAlpha($str);$str = "123ABccAAA";printIsAlpha($str);$str = "A B";printIsAlpha($str);function printIsAlpha($str){echo "The string is: ". $str. "\n";echo "Is Alpha: ";var_dump(ctype_alpha($str));echo "---------\n";}?>
Explanation
In the code above:
-
We used the
ctype_alphamethod to check if the string contains only alphabetical characters. -
For the
abcstring, thectype_alphareturnstrue. -
But for the
123ABccAAAstring, thectype_alphamethod returnsfalse, because the string contains numeric characters. -
Similarly, for
A B, thectype_alphamethod returnsfalsebecause the non-alphabetical character space is present in the string.
Point to be noted
If an int value from -128 to 128 is passed as an argument, then it is internally converted as an ASCII character and checked to see if the converted character is an alphabet. For example:
<?phpvar_dump(ctype_alpha(97));?>
In the code above, we passed 97 as an argument. It is internally converted as ASCII character a and checked to see if it is an alphabet. a is a valid alphabet, so true is returned.