Capitalize string in PHP
In this blog post, you will learn how you can capitalize a string in PHP. We will not use any external library for this purpose. This code can be used in any PHP framework (Laravel, Yii) because I have not used any dependency for it. We will also teach you, how you can update the array element inside foreach loop in PHP.
First, we will explode the string by space.
<?php
// input string
$str = "adnan afzal";
// split words by space
$parts = explode(" ", $str); // ["adnan", "afzal"]
- explode(delimiter, string): This is a PHP built-in function used to split the string into an array using a delimiter. Here, we are splitting the string using space. So it will return an array of all words in a string.
Then we will loop through all words one-by-one:
// loop through each word
foreach ($parts as $key => $value)
{
// [section-1]
}
Inside the loop, we will update the word by uppercasing the first letter of each word. Write the following code in [section-1]:
// make first letter uppercase
// and update the word
$parts[$key] = ucfirst($value); // converts ["adnan"] to ["Adnan"]
- ucfirst(string): This is another PHP built-in function and it is used to uppercase the first letter of the string. So “adnan” will became “Adnan”.
We are converting all the words first letter to uppercase and update the word itself. You can update the array value inside foreach loop using the $key variable.
After the loop, we will join all array parts by space.
// join all words by space
$str = implode(" ", $parts); // converts ["Adnan", "Afzal"] to "Adnan Afzal"
// output string
echo $str;
- implode(glue, pieces): This function will join the array into a string using a glue. In this case, we are joining the array using space.
Complete code
Following is the complete code to capitalize the string in PHP:
<?php
// input string
$str = "adnan afzal";
// split words by space
$parts = explode(" ", $str); // ["adnan", "afzal"]
// loop through each word
foreach ($parts as $key => $value)
{
// make first letter uppercase
// and update the word
$parts[$key] = ucfirst($value);
}
// join all words by space
$str = implode(" ", $parts);
// output string
echo $str;
Bonus
There might be some cases where you have a value in database like “processing_order” and you want it to display like “Processing Order”. In this case, you just have to add 1 line before using explode() function.
$str = "processing_order";
$str = str_replace("_", " ", $str); // processing order
Then you can apply the above code to capitalize the string. If you want to learn how to capitalize string in Javascript, follow this.