In PHP programs we sometimes need to convert the cases of letters in strings. For example, we may have a lowercase string
and require an Uppercase string
.
It would be possible to iterate over the characters in a string
and convert them. But it is much easier to use a built-in function like strtoupper
.
This program introduces several strings and then converts them with built-in functions. It prints the resulting strings.
strtoupper
. This takes all lowercase characters and changes them to uppercase.strtolower
, we convert characters that are already uppercase, and change them to lowercase.strtoupper
), digits, punctuation and whitespace are left alone.// Part 1: convert a string to uppercase. $value = "bird"; $upper = strtoupper($value); var_dump($upper); // Part 2: convert a string to lowercase. $value = "CAT"; $lower = strtolower($value); var_dump($lower); // Part 3: non-letters are not affected. $value = "123 z?"; $upper = strtoupper($value); var_dump($upper);string(4) "BIRD" string(3) "cat" string(6) "123 Z?"
There are some helpful functions in the PHP standard library that only convert the first letter in strings. And we can even target each word in a single call.
string
. If the first character is not a letter, the function has no effect.ucwords
, we uppercase each letter that is either the first letter in the string, or follows a space character.// Part 1: uppercase first letter. $value = "test"; $result = ucfirst($value); var_dump($result); // Part 2: lowercase first letter. $value = "TEST"; $result = lcfirst($value); var_dump($result); // Part 3: uppercase all words. $value = "one two three"; $result = ucwords($value); var_dump($result); // Part 4: words begin after a space only. $value = "one-two, hello"; $result = ucwords($value); var_dump($result);string(4) "Test" string(4) "tEST" string(13) "One Two Three" string(14) "One-two, Hello"
Sometimes in programs we need to normalize the casing of strings—for example, all data should be lowercase. Functions like strtolower
are ideal for this purpose.