Get Initials
Extract initials from a full name. Given a string containing a person's full name, return their initials in uppercase separated by dots.
Write a PHP function that extracts initials from a name. Use explode(' ', \$name) to split into words. Loop through each word, take the first character with \$word[0], convert to uppercase with strtoupper(), and collect in an array. Join with implode('.', \$initials).
The bracket notation \$word[0] gets the first byte of the string which is the first character for ASCII names. The space delimiter splits on word boundaries. Empty names return empty string. Multiple spaces between words are handled by checking if \$w is not empty.
Edge cases include empty strings (return ''), single-word names, and names with multiple middle names.
Time complexity is O(n). Space complexity is O(n).
The initials extraction problem teaches string splitting and character access in PHP. The explode() function splits a string by a delimiter, returning an array of substrings. Accessing the first character with bracket notation ($str[0]) works for single-byte characters.
This technique is commonly used in name formatting for IDs, email addresses, or directory listings. The strtoupper() function ensures consistent capitalization regardless of input case.
Example Input & Output
Algorithm Flow

Solution Approach
Write a PHP function that extracts initials from a name. Use explode(' ', \$name) to split into words. Loop through each word, take the first character with \$word[0], convert to uppercase with strtoupper(), and collect in an array. Join with implode('.', \$initials).
The bracket notation \$word[0] gets the first byte of the string which is the first character for ASCII names. The space delimiter splits on word boundaries. Empty names return empty string. Multiple spaces between words are handled by checking if \$w is not empty.
Edge cases include empty strings (return ''), single-word names, and names with multiple middle names.
Time complexity is O(n). Space complexity is O(n).
Best Answers
<?php
function getInitials($name) {
$words = explode(' ', $name);
$initials = [];
foreach ($words as $w) {
if ($w !== '') $initials[] = strtoupper($w[0]);
}
return implode('.', $initials);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
