Web Development

Interesting ucfirst()

For [code]ucfirst()[/code] function we can say that one of the simple php function. But sometimes this simple function can also create a confusion for you.

Normally we perform this function on lower cased string. But have you tried to apply this function to Upper cased string.

Basically we can understand that [code]ucfirst()[/code] will operate on whole string and make only first character to upper case. But this is not the case.

ucfirst() to lower cased string:

[cc lang=”php”]
$str = “this is the string”;
echo ucfirst($str);
// OUTPUT
// This is the string
[/cc]

ucfirst() to upper cased string:

[cc lang=”php”]
$str = “THIS IS THE STRING”;
echo ucfirst($str);
// OUTPUT
// THIS IS THE STRING
[/cc]

This is because, [code]ucfirst()[/code] function will operate only on first character of the string rather than whole string.

Shares:
  • huarong
    August 30, 2011 at 6:38 am

    Can’t quite follow you.

    Reply
    • Avinash
      August 30, 2011 at 9:11 am

      Hi huarong,

      No problem at all, But actually I was surprised with the result. So i thought it is good to share :)

      Reply
  • Karoly Bujtor
    Karoly Bujtor
    August 31, 2011 at 12:50 pm

    Well, it seems logical that ucfirst() doesn’t change the case of any uppercase character in a string.

    You can use ucfirst(strtolower($str)) if you want only the first character uppercase and the others lowercase.

    Reply
    • Avinash
      August 31, 2011 at 10:28 pm

      Yes that’s what I have done then after.. :)

      Reply
  • Aaron
    Aaron
    September 16, 2011 at 6:48 pm

    Use ucwords() if you want to change “this is a test” into “This Is A Test.”

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *