ctype_alpha(): Validating only alphabetic characters

$var="abcdef"; // This is alphabetic
//$var="abc=123"; // This is NOT alphabetic
//$var="123"; // This is NOT alphabetic
//$var='xyz12'; // This is NOT alphabetic
//$var='123.56'; // This is NOT alphabetic
//$var=123;  // This is NOT alphabetic

if(ctype_alpha($var)){
	echo " This is alphabetic  ";
}else{ 
	echo " This is NOT alphabetic ";
}
Syntax
bool ctype_alpha(string $input_string)
Returns True or False

By changing the value of $var you can check this function.

By using ctype_alpha function in php we can check or validate alphabetic characters only. Using this function we can check any input coming from insecure ( or any other ) sources. This function is case insensitive so can't differentiate between lower case and upper case alphabetic characters.
We can check user input from a web form for presence of alphabets only, here is the sample code.
if(ctype_alpha($_POST['var'])){
echo " This is alphabetic ";
}else{ echo "this is not alphabetic";}

Checking Array

We can check each element of an array.
$ar=array('abc','as12',123,'ab#1','@12');
foreach ($ar as $var){
if(ctype_alpha($var)){
	echo " $var  is alphabetic  ";
}else{ 
	echo " $var is NOT alphabetic ";
}
echo "<BR>";
}
output
abc is alphabetic
as12 is NOT alphabetic
123 is NOT alphabetic
ab#1 is NOT alphabetic
@12 is NOT alphabetic

Example: Validating a Username

$username = "JohnDoe";
if (ctype_alpha($username)) {
    echo "Valid username";
} else {
    echo "Invalid username";
}

Example: Handling Strings with Spaces

$str = "Hello World";
if (ctype_alpha($str)) {
    echo "Valid string";
} else {
    echo "Invalid string";  // Output: Invalid string
}

Example: Comparing with preg_match()

$str = "JohnDoe";
if (preg_match('/^[a-zA-Z]+$/', $str)) {
    echo "Valid alphabetic string";
} else {
    echo "Invalid string";
}

To check only alphanumeric characters we can use ctype_alnum function.

Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer