Code Logo

Get Initials

Published at24 Jul 2026
PHP String Handling Easy 0 views
Like0

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

Example 1
Input
"john doe"
Output
"J.D"
Example 2
Input
"A"
Output
"A"
Example 3
Input
""
Output
""
Example 4
Input
"John Doe"
Output
"J.D"
Example 5
Input
"John Michael Doe"
Output
"J.M.D"

Algorithm Flow

Recommendation Algorithm Flow for Get Initials
Recommendation Algorithm Flow for Get Initials

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 - Approach 1
<?php
function getInitials($name) {
    $words = explode(' ', $name);
    $initials = [];
    foreach ($words as $w) {
        if ($w !== '') $initials[] = strtoupper($w[0]);
    }
    return implode('.', $initials);
}