What is the ctype_alnum method in PHP?

The ctype_alnum method is used to check if all the characters of the text are alphanumeric.

Syntax

ctype_alnum(mixed $text): bool

The ctype_alnum method returns a Boolean value.

The alphanumeric characters are A-Z, a-z, and 0-9.

ctype_alnum returns true if and only if all of the characters in the text are alphanumeric. Otherwise, it returns false.

Example

<?php
$str = "abc";
printAlphaNumeric($str);
$str = "123ABccAAA";
printAlphaNumeric($str);
$str = "A B";
printAlphaNumeric($str);
function printAlphaNumeric($str){
echo "The string is: ". $str. "\n";
echo "Alphanumeric: ";
var_dump(ctype_alnum($str));
echo "---------\n";
}
?>

In the code above:

  • We use the ctype_alnum method to check if the string contains only alphanumeric characters.

  • For the string abc and 123ABccAAA, ctype_alnum returns true.

  • For the string A B, the ctype_alnum method returns false because the string contains the space character, which is not an alphanumeric character.

Free Resources