Initials from a full name
A conference badge printer squeezes each attendee's name down to initials. Read a full name made of one to five words separated by single spaces and print the first letter of every word, converted to uppercase and joined with nothing in between.
Input
One line: 1 to 5 words of ASCII letters, separated by single spaces.
Output
One line: the initials in uppercase.
Example 1
Input
ada marsh
Output
AM
The first letters of ada and marsh, uppercased.
Example 2
Input
mo van der berg
Output
MVDB
Every word counts, including short ones like van and der.
Constraints
- Each word has 1 to 30 ASCII letters
- Words are separated by exactly one space
Hints
Hint 1 of 3
explode(' ', $name) splits the line into an array of words.
Hint 2 of 3
$word[0] is the first character of a string, and strtoupper() uppercases it.
Hint 3 of 3
Build the result with .= inside a foreach, then echo it once.
Solution
Show a reference solution and explanation
<?php
$name = trim(fgets(STDIN));
$initials = '';
foreach (explode(' ', $name) as $word) {
$initials .= strtoupper($word[0]);
}
echo $initials, "\n";
Why it works
The three steps are split, pick and join. explode() turns the line into an array of words; indexing a string with [0] gives its first byte, which is the first letter for ASCII input; strtoupper() converts it. Appending to a string with .= inside the loop keeps the code simple, and printing once at the end avoids stray output. For names with accented letters you would need mb_substr() and mb_strtoupper(), because a single byte is no longer a single character.
Lesson for this exercise: Strings in PHP