String Uppercase Examples
This page was last reviewed on May 29, 2023.
Dot Net Perls
Uppercase. 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.
Loop, String Chars
Example. This program introduces several strings and then converts them with built-in functions. It prints the resulting strings.
Part 1 We invoke strtoupper. This takes all lowercase characters and changes them to uppercase.
Part 2 With strtolower, we convert characters that are already uppercase, and change them to lowercase.
Part 3 For these functions (like 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?"
First letters. 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.
Part 1 We call ucfirst to uppercase the first letter in a string. If the first character is not a letter, the function has no effect.
Part 2 We lowercase the first letter. All the remaining letters are left unchanged.
Part 3 With ucwords, we uppercase each letter that is either the first letter in the string, or follows a space character.
Part 4 Ucwords will not handle uppercasing the letter after a hyphen or other non-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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 29, 2023 (new).
© 2007-2024 Sam Allen.