PHP – What in the world is CType
Apparently the name comes from ctype.h, a file in the C programming language. The PHP engine can execute the code from that file in it’s ctype functions. Does the c in ctype stand for classification, or character maybe? I don’t know, but according to PHP, these functions “are always preferred over regular expressions, and even to some equivalent str_* and is_* functions.” because they are executed from the executable functions (from ctype.h) and are therefore faster.
$is_it_alphanumeric = ctype_alnum("Carnival101"); //true $is_it_alphanumeric_too = ctype_alnum("Carnival*_*");//false $is_it_alphanumeric_also = ctype_alnum("Carnival1.01"); //false
ctype_alnum() checks if the string is totally alphanumeric. The first of those was the only one, a decimal is still not going to return true. Checking if things are alphanumeric is actually pretty useful, but it’s probably more common to check if it is an unsigned integer for example.
$is_it_digit = ctype_digit("05909090"); //true $is_it_digit_too = ctype_digit(-4); //false $is_it_digit_also = ctype_digit(4.5); //false
So only 0s to 9s will get you a true result. Positive integers will also work. ctype_alpha() is the same as those 2 but for letters only. Going back to ctype_alnum, it also accepts integers but “If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character ” So if you aren’t interested in ASCII tests don’t pass integers to ctype_alnum(). That rule applies to the next function as well, called ctype_print();
ctype_print("asdf\n\r\t"); // false
ctype_print() only returns true if the characters are printable and not control characters. This is a confusing classification, since spaces would be allowed and tabs not. Only use it if you are looking for a very specific type of check. ctype_graph() might be more clear, as it is the same but spaces are not valid, no white space is allowed. ctype_cntrl() is the opposite of ctype_print(), the characters must be control characters to get it to return true.
ctype_lower() returns true for lowercase letters only
ctype_punct() returns true for punctuation only
ctype_space() returns true for white space only (tab, space, newline and so on)
ctype_xdigit() returns true for hexidecimal characters only (comes in useful for checking if the string is a color code for example)
ctype_upper returns true for uppercase letters only
For all these functions, empty strings will give you false in new versions of PHP, but true in older versions (< 5.1). Passing something other than an integer or string will return false.