a shot of dev knowledge

RELATED TAGS

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-Z and lower case a-z characters.

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_alpha method to check if the string contains only alphabetical characters.

  • For the abc string, the ctype_alpha returns true.

  • But for the 123ABccAAA string, the ctype_alpha method returns false, because the string contains numeric characters.

  • Similarly, for A B, the ctype_alpha method returns false because 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:

<?php 
    var_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.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring