Code Logo

Capitalize Name

Published at24 Jul 2026
PHP String Handling Easy 0 views
Like0

Capitalize the first letter of each word in a name.

Write a PHP function that capitalizes each word in a name. Use ucwords(\$name) which capitalizes the first character of each word. Words are delimited by whitespace.

For a manual implementation: explode() by space, apply ucfirst() to each word, then implode(). This allows custom handling of edge cases like multiple spaces or specific delimiters.

Edge cases include empty strings (return ''), single-word names, names with existing mixed case, and names with numbers or special characters.

Time complexity is O(n). Space complexity is O(n).

Name capitalization is useful for formatting user input consistently. The ucwords() function capitalizes the first letter of each word in a string, handling most common name formats automatically. For names with unusual capitalization, ucwords() preserves the case of non-first letters.

This function is commonly used in user registration systems to standardize name formatting. PHP's string functions make this operation a single function call, demonstrating the power of PHP's built-in text processing capabilities.

The manual approach using explode(), ucfirst(), and implode() gives more control and is useful when names contain special characters or multiple spaces between words.

Example Input & Output

Example 1
Input
"john doe"
Output
"John Doe"
Example 2
Input
"john"
Output
"John"
Example 3
Input
"JOHN DOE"
Output
"JOHN DOE"
Example 4
Input
"a b c"
Output
"A B C"
Example 5
Input
""
Output
""

Algorithm Flow

Recommendation Algorithm Flow for Capitalize Name
Recommendation Algorithm Flow for Capitalize Name

Solution Approach

Write a PHP function that capitalizes each word in a name. Use ucwords(\$name) which capitalizes the first character of each word. Words are delimited by whitespace.

For a manual implementation: explode() by space, apply ucfirst() to each word, then implode(). This allows custom handling of edge cases like multiple spaces or specific delimiters.

Edge cases include empty strings (return ''), single-word names, names with existing mixed case, and names with numbers or special characters.

Time complexity is O(n). Space complexity is O(n).

Best Answers

php - Approach 1
<?php
function capitalizeName($name) {
    return ucwords($name);
}