Open In App

How to convert the first character to uppercase using PHP ?

A string is a combination of words combined together. The first character of the string can be converted to an upper case in case it is a lower case alphabetic character. 

Approach 1 : Using chr() method



The substr() method can be used to extract from the second character of the string till the length of the string. The first character converted to the upper case can then be concatenated to the obtained substring to get the final string. 

Example:




<?php
  //declaring string
  $str = "how!to?code? in geeksforgeeks";
  print("Original String : ".$str."\n<br/>"); 
//getting first char
  $ch = $str[0];
//converting to upper case
  $upper = chr(ord($ch)-32);
//appending the first remaining string to upper case character
  $fin_str = $upper.substr($str,1);
  print("Modified String : ".$fin_str);
?>

Output
Original String : how!to?code? in geeksforgeeks
Modified String : How!to?code? in geeksforgeeks

Approach 2 : Using ucfirst() method

The ucfirst() method takes an input string and converts its first character to the uppercase, if it is a lower case alphabetic character. The output has to be saved in a variable to retain the changes. 

ucfirst ( str )

Example:




<?php
     
  $str = "how!to?code? in geeksforgeeks";
  print("Original String : ".$str."\n<br/>"); 
  $upper = ucfirst($str);
  print("Modified String : ".$upper);
?>

Output
Original String : how!to?code? in geeksforgeeks
Modified String : How!to?code? in geeksforgeeks

Approach 3 : Using strtoupper() method

Example:




<?php
  //declaring string
  $str = "how!to?code? in geeksforgeeks";
  print("Original String : ".$str."\n<br/>"); 
//getting first char
  $ch = $str[0];
//converting to upper case
  $upper = strtoupper($ch);
//appending the first remaining string to uppercase character
  $fin_str = $upper.substr($str,1);
  print("Modified String : ".$fin_str);
?>

Output
Original String : how!to?code? in geeksforgeeks
Modified String : How!to?code? in geeksforgeeks

Article Tags :