-4

I don't understand this:

[1]

<?php
$test="HELLO WORLD";
echo ucwords($test);
// it will print HELLO WORLD
?>

[2]

<?php
$test="HELLO WORLD";
echo ucwords(strtolower($test));
// it will print Hello World
?>

Why use strtolower when converting a string to capitalize from uppercase?

3 Answers3

7

From the documentation for ucwords():

Returns a string with the first character of each word in str capitalized, if that character is alphabetic.

ucwords() only cares about the first character of the word. It leaves the rest untouched.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
3

ucwords() does not convert the string to lowercase before converting the first letter of each word to uppercase. Nor does it convert the non-first letters to lowercase. It only converts the first letters to uppercase.

That is why you must explicitly convert those letters to lowercase before using ucwords().

John Conde
  • 217,595
  • 99
  • 455
  • 496
1

In the following code The variable $test is uppercase. The ucwords Changes only the first letter of each word. You can't see changes and the result with the variable are same.

[1]

<?php
$test="HELLO WORLD";
echo ucwords($test);
// it will print HELLO WORLD
?>

In the second code... All the string variable first converted to lower case with strtolower function and then the ucwords function changes all first characters from the words as uppercase.

With strtolower the result is => "hello world"

After, the ucwords result is "Hello World".

[2]

<?php
$test="HELLO WORLD";
echo ucwords(strtolower($test));
// it will print Hello World
?>