An Introduction to Ctype Functions

Share this article

The Ctype extension provides a set of functions that are used to verify whether the characters in a string are of the correct type. In this article we’ll take a look at the syntax used by the character type functions, see what specific functions exist, and how they are used to perform validation. The extension is enabled by default if you’re running PHP 4.2 or above. If you cannot stand the thought of this extension running with your installation for some crazy reason, then you can use the --disable-ctype compile switch to turn it off. If you have a background in C, then you’re probably already familiar with the character type functions because that is where they come from (don’t forget that PHP is actually written in C). But if you’re into Python, then it’s only fair to point out that the PHP Ctype functions have absolutely nothing to do with the Python’s ctypes library. It’s just one of those tragic and totally unavoidable naming similarities.

So How Does it Work?

It’s all very simple. As I noted before, the functions check a string value to see if the characters are within a given range or that every character is of the appropriate type. For example, you can use these functions to see if a string contains only uppercase characters, or if it’s numeric, or if it consists of hex characters, or one of the other dozen or so options available. You should be diligent in making sure you always pass in a string. Sure, you can pass in integers, but you’re setting yourself up for trouble as the PHP manual notes on every function’s page:
If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.
This example from the ctype_digit() page illustrates the effect of this:
<?php
$numeric_string = "42";
$integer        = 42;

ctype_digit($numeric_string); // true
ctype_digit($integer);        // false (ASCII 42 is '*')

is_numeric($numeric_string);  // true
is_numeric($integer);         // true
If we look at the code above, the first line evaluates as true. The second statement, however, is false. It is true that 42 is an integer, but the ctype statement evaluates it as a single ASCII character which in this case is an asterisk. Ctype functions are not the only way to validate data, of course. You can also use the is_numeric() function, depending on your needs. It treats a numeric as just that, a number, and returns true value as shown below:
<?php
is_numeric($numeric_string);  // true
is_numeric($integer);         // true
There are also other is_* functions, including is_float()
, is_integer(), etc. Why are we talking about is_* functions here? Just to remind you there is more than one way to skin a cat. Actually, in today’s age I’m probably not supposed to say that. It’s just an expression. Don’t skin your cat and then tell everyone it was my idea. It’s just that there are multiple ways of doing things.

What Functions are Available

I’ve hinted that a wide range of checking is available, but what exactly are the functions available? What kind of checking is available? The list is below.
  • ctype_alnum() – check for alphanumeric characters (A – Z, upper or lower case, 0-9, no special characters, punctuation, or other freaks).
  • ctype_alpha() – check for alphabetical characters (A-Z, upper or lower case).
  • ctype_cntrl() – check for control characters (things like n, etc.).
  • ctype_digit() – check for numeric characters (0-9, no decimal point, comma, etc.).
  • ctype_graph() – check for visually printable characters (not control characters or space).
  • ctype_lower() – check for lowercase characters (a-z lower case only, no numbers).
  • ctype_print() – check for printable characters including control characters and space.
  • ctype_punct() – check for punctuation type characters (no numbers, letters, or space). Generally these include many of the “swear word” characters that we often call “special” characters. @&!#
  • ctype_space() – check for whitespace characters (includes blanks and any control character that leaves a space on the page, such as “Narrow No-Break Space” and the “Mongolian Vowel Separator”).
  • ctype_upper() – check for uppercase characters (A-Z upper case only, no numbers or special characters).
  • ctype_xdigit() – check for hex characters.

How to Use Them

Using the Ctype functions is pretty easy. You just set it up, generally, in an if-statement, sometimes embedded in a loop if you’re testing a number of values from in an array, and then check if the result of the function call is true or false. True means that every character in that string is the type of character called for by that specific function. Here’s an example:
<?php
if (ctype_alnum($string)) {
    echo "This string totally works";
}
else {
    echo "And this one not so much";
}
If the value of $string is “Azxc1234” then you’ll see the message that it works. If $string
is “123#Axy” then it won’t because # is not an alphanumeric character. Note that if you pass in an empty string, the functions will false in PHP 5.1 and above, but true if you are on an earlier version (just another reason to upgrade now!). And also remember to make sure the input to a Ctype function is a string! When in doubt, there’s no harm in casting it.
<?php
$integer = 42;

ctype_digit($integer);         // false
ctype_digit((string)$integer); // true

Conclusion

And that’s all there is to it! The functions should inherently be part of your PHP installation (if not then you definitely need to upgrade or stop setting up weird PHP set ups). And they are simple to use so long as you only input strings. So where would you use them? Well, anytime you need to bring a string in from a form you could use them to test the validity of the data you are dealing with. Really, the sky’s the limit. (Fortunately, I don’t have to take a public or private stand on what you use them for; I just say what the functions are and how to use them). Image via Fotolia

Frequently Asked Questions (FAQs) about Ctype Functions in PHP

What are the main uses of ctype functions in PHP?

Ctype functions in PHP are used to check if the type or the value of a specific character or string matches certain conditions. These functions are particularly useful when you need to validate input or check the format of data. For instance, you can use ctype_digit() to check if a string consists only of digits, or ctype_alpha() to check if a string consists only of letters.

How can I enable ctype functions in PHP?

Ctype functions are enabled by default in PHP. However, if you find that they are not available, you may need to install or enable the ctype extension. This can be done by uncommenting the line “extension=ctype” in your php.ini file and restarting your web server. If the extension is not installed, you may need to install it using your server’s package manager.

Can I use ctype functions with non-string data types?

Ctype functions are designed to work with strings. If you pass a non-string value to a ctype function, it will be converted to a string before the function is applied. This can lead to unexpected results if the value cannot be accurately represented as a string. Therefore, it is recommended to always use strings with ctype functions.

Are ctype functions case-sensitive?

Yes, ctype functions are case-sensitive. For example, ctype_alpha() will return true for ‘abc’ but false for ‘ABC’. If you want to perform a case-insensitive check, you can convert the string to lowercase or uppercase using the strtolower() or strtoupper() function before passing it to the ctype function.

How can I check if a string contains only alphanumeric characters using ctype functions?

You can use the ctype_alnum() function to check if a string contains only alphanumeric characters. This function will return true if the string consists only of letters and digits, and false otherwise.

What is the difference between ctype_digit() and is_numeric()?

While both functions are used to check if a string contains numeric values, there is a key difference. The ctype_digit() function will return true only if the string consists solely of digits. On the other hand, is_numeric() will return true if the string contains any numeric value, including floating point numbers and numbers in scientific notation.

Can ctype functions handle multibyte characters?

No, ctype functions cannot handle multibyte characters. They are designed to work with ASCII characters only. If you need to work with multibyte characters, you should use the mbstring extension instead.

Are ctype functions available in all versions of PHP?

Ctype functions have been available in PHP since version 4.0.4. However, they are not enabled by default in all versions. In PHP 5.2.0 and later, they are enabled by default.

Can I use ctype functions to validate user input?

Yes, ctype functions are commonly used to validate user input. They can help ensure that the input matches the expected format, which can help prevent errors and security vulnerabilities.

How can I check if a string contains only whitespace using ctype functions?

There is no specific ctype function to check for whitespace. However, you can use the ctype_space() function to check if a string contains only whitespace characters. This function will return true if the string consists only of whitespace characters, and false otherwise.

David ShireyDavid Shirey
View Author

Dave Shirey is owner of Shirey Consulting Services which provides business and technical project management, EDI set up and support, and various technical services for the mainframe, midrange, and desktop worlds. In addition to PHP Master, he also writes frequently for MC Press and Pro Developer (formerly System iNews). In his free time, he tends to worry vaguely about the future and wonder obsessively how different his life might have been if he had just finished working on that first novel when he got out of college.

Beginner
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form