PHP Capitalize First Letter with Best Example

PHP has many built-in functions that make the first letter capital.

We are going to show you three methods on how to capitalize the first letter of a string in PHP.

How to capitalize the first letter of a String in PHP?

The following are the methods to capitalize the first letter in PHP:

Method 1: Using ucfirst() function

The ucfirst() function converts the first character of a string to uppercase.

Syntax:

ucfirst( string )

Parameters:

ParameterDescription
stringSpecifies the string that should be converted.

Example 1:

Below is an example of how to use the ucfirst() function.

<?php
    $str = "itsourcecode";
    echo ("Original: ".$str);
    echo ("<br>");
    echo ("Capitalized: ".ucfirst($str));
?>

Output:

Original: itsourcecode
Capitalized: Itsourcecode

Example 2:

If we wish to convert only the first letter of a string to uppercase and the rest to lowercase, we can use the strtolower() function in combination with the ucfirst() function.

<?php
    $str = 'itSourceCode';
    echo ("Original: ".ucfirst($str));
    echo "<br>";
    echo ("Capitalize: ".ucfirst(strtolower($str)));
?>

Output:

Original: ItSourceCode
Capitalize: Itsourcecode

Method 2: Using chr() function

The chr() function returns a character from the specified ASCII value.

Syntax:

chr( ascii )

Parameters:

ParameterDescription
asciiAn ASCII value

  • Step 1: The initial index can be used to retrieve the first character of a string; str[0] returns the first character of the input string.
  • Step 2: Using the ord() function and a negative of 32 from the character’s ASCII value, the retrieved character can be transformed into upper case. The uppercase character’s resulting ASCII value is subsequently transformed into a character using the chr() method.
  • Step 3: The substr() method returns a part of the original string between the start and end indexes.

The substr() method can be used to get the string from the second character to the end of the string.

The final string is made by adding the first character that was changed to upper case to the substring that was found.

Example:

<?php
    // This is the declaration of string
    $str = "where source code is not a problem";
    echo ("Original: ".$str);
    echo ("<br>");
    
    // This is to get the first character
    $gfc = $str[0];
    
    // This is converting the first character to uppercase
    $conv_upper = chr(ord($gfc)-32);
    
    // This is to append the first remaining string to upper case character
    $str2 = $conv_upper.substr($str,1);
    print("Capitalized: ".$str2);
?>

Output:

Original: where source code is not a problem
Capitalized: Where source code is not a problem

Method 3: Using strtoupper() function

The strtoupper() function converts a string to uppercase.

Based on PHP official documentation, strtoupper() makes a string uppercase.

Syntax:

strtoupper( string )

Parameters:

ParameterDescription
stringSpecifies the string that should be converted.

Step 1: 

The initial index can be used to retrieve the first character of a string; str[0] returns the first character of the input string.

Step 2: 

Using the strtoupper() method, which accepts a string as input and changes it to upper case, the character taken from the string can be transformed to upper case.

Since a character is also a string, it can be passed to this method as input.

Step 3: 

In this example, the substr() method can be used to extract from the second character of the string to the string’s length.

Concatenating the initial character changed to upper case with the resulting substring produces the final string.

Example:

<?php
    // This is the declaration of string
    $str = "where source code is not a problem";
    echo ("Original: ".$str);
    echo ("<br>");
    
    // This is to get the first character
    $gfc = $str[0];
    
    // This is converting the first character to uppercase
    $conv_upper = strtoupper($gfc);
    
    // This is to append the first remaining string to upper case character
    $str2 = $conv_upper.substr($str,1);
    print("Capitalized: ".$str2);
?>

Output:

Original: where source code is not a problem
Capitalized: Where source code is not a problem

Frequently Asked Questions (FAQs)

How do you capitalize words in PHP?

The ucwords() function changes to uppercase the first letter of each word in a string.

Note: This function is binary-safe.

Is PHP all capital letters?

The strtoupper() method is one of the most extensively used functions in PHP for converting strings to uppercase. It accepts a string as an argument and converts all lowercase characters to uppercase. Other characters in the string, such as numerals and special characters, stay unchanged.

How will you capitalize the first letter of string?

To capitalize the first character of a string, we can separate it using the charAt() method and then capitalize it using the toUpperCase() function.

Summary

In summary, the best way to capitalize the first letter in PHP is by using the ucfirst() function.

Lastly, if you want to learn more about capitalizing the first letter in PHP, please leave a comment below. We’ll be happy to hear it!

Common use cases for PHP Capitalize First Letter with Best Example

  • Web application development. Full-stack PHP apps using vanilla PHP or Laravel/Symfony frameworks.
  • WordPress plugin/theme development. Custom functionality for the world’s most popular CMS.
  • API development. REST or GraphQL endpoints serving mobile apps and SPAs.
  • CLI tools. Command-line scripts for cron jobs, data migration, or automation.
  • Legacy code maintenance. PHP powers a large share of the web; understanding it is a durable skill.

Working code example

<?php
declare(strict_types=1);

class UserService {
    public function getGreeting(string $name): string {
        if ($name === "") {
            throw new InvalidArgumentException("Name is required");
        }
        return "Welcome, " . htmlspecialchars($name);
    }
}

$service = new UserService();
echo $service->getGreeting("Alice");
?>

Best practices

  • Enable strict types. declare(strict_types=1) at the top of every file catches type coercion bugs.
  • Use Composer. Modern PHP uses Composer for dependency management, autoloading, and PSR-4 class naming.
  • Follow PSR standards. PSR-12 for coding style, PSR-4 for autoloading, PSR-3 for logging.
  • Write unit tests with PHPUnit. Aim for 70%+ code coverage on business-critical modules.
  • Use static analysis. PHPStan or Psalm catch many bugs before code runs.

Common pitfalls

  • Global state. Overusing global variables makes testing hard. Prefer dependency injection.
  • SQL concatenation. Always use prepared statements. Never concatenate user input into SQL strings.
  • Missing type declarations. Old PHP allowed loose types. Modern PHP encourages strict typing everywhere.
  • Ignoring errors. Set error_reporting(E_ALL) in development. Handle errors explicitly in production.

Frequently Asked Questions

What PHP version does this tutorial target?
This tutorial is written for PHP 8.0 or higher. Modern features (arrow functions, named arguments, match expressions, enums, nullsafe operator) work best in PHP 8.1+. For legacy PHP 7.x, most examples still run but with fallback syntax.
Do I need XAMPP to run PHP code examples?
For beginners, XAMPP (Apache + PHP + MySQL) is the easiest setup on Windows. On Mac, use MAMP or Homebrew php. On Linux, install php-cli via apt or yum. For quick one-off tests, use an online PHP sandbox like PHP Sandbox or 3v4l.org.
How do I test the code snippets in this tutorial?
Save each example as a .php file inside XAMPP htdocs folder, start Apache in XAMPP Control Panel, then open http://localhost/yourfile.php in a browser. For pure PHP CLI code, run php yourfile.php from the terminal.
Can I use this in a Laravel project?
Yes. Most native PHP functions covered in these tutorials work identically inside Laravel. Some Laravel helpers (str_helpers, arr_helpers) provide framework-specific wrappers around the same functions.
Where can I get more PHP practice projects?
Browse itsourcecode.com PHP Projects for 300+ free capstone-ready systems (POS, inventory, hospital management, e-commerce). Each includes source code, database SQL, and installation guide for BSIT capstone students.

Leave a Comment