0
0
PhpProgramBeginner · 2 min read

PHP Program to Capitalize First Letter of a String

Use the PHP function ucfirst() to capitalize the first letter of a string, for example: ucfirst('hello') returns 'Hello'.
📋

Examples

Inputhello
OutputHello
Inputphp programming
OutputPhp programming
Input123abc
Output123abc
🧠

How to Think About It

To capitalize the first letter of a string, identify the first character and convert it to uppercase while leaving the rest of the string unchanged. PHP provides a built-in function ucfirst() that does exactly this.
📐

Algorithm

1
Get the input string.
2
Use a function to convert the first character to uppercase.
3
Keep the rest of the string as it is.
4
Return or print the modified string.
💻

Code

php
<?php
$input = 'hello';
$output = ucfirst($input);
echo $output;
?>
Output
Hello
🔍

Dry Run

Let's trace the input 'hello' through the code.

1

Input string

The input string is 'hello'.

2

Apply ucfirst()

The function changes the first character 'h' to 'H'.

3

Output string

The output string becomes 'Hello'.

StepInputOutput
1hellohello
2helloHello
3HelloHello
💡

Why This Works

Step 1: Identify first character

The function ucfirst() looks at the first character of the string.

Step 2: Convert to uppercase

It converts that first character to uppercase if it is a letter.

Step 3: Keep rest unchanged

The rest of the string remains exactly the same.

🔄

Alternative Approaches

Using substr and strtoupper
php
<?php
$input = 'hello';
$output = strtoupper(substr($input, 0, 1)) . substr($input, 1);
echo $output;
?>
This method manually changes the first letter and concatenates the rest; useful if you want more control.
Using mbstring for multibyte strings
php
<?php
$input = 'héllo';
$output = mb_strtoupper(mb_substr($input, 0, 1)) . mb_substr($input, 1);
echo $output;
?>
This handles multibyte characters correctly, unlike <code>ucfirst()</code> which may fail with special characters.

Complexity: O(n) time, O(n) space

Time Complexity

The function processes the string once, mainly changing the first character, so it runs in linear time relative to the string length.

Space Complexity

A new string is created with the first letter capitalized, so space usage is proportional to the input string length.

Which Approach is Fastest?

ucfirst() is the fastest and simplest for ASCII strings; manual methods add overhead but allow more control or multibyte support.

ApproachTimeSpaceBest For
ucfirst()O(n)O(n)Simple ASCII strings
substr + strtoupperO(n)O(n)Manual control over string parts
mbstring methodO(n)O(n)Multibyte and Unicode strings
💡
Use ucfirst() for simple capitalization of the first letter in ASCII strings.
⚠️
Forgetting that ucfirst() only changes the first character and leaves the rest unchanged, so the rest may still be lowercase.