String Length and Case

Measure a string with strlen() and change its case with the case functions.

Syntaxstrlen($string);

PHP has many built-in string functions. Some of the most common:

  • strlen() — returns the number of characters.
  • strtoupper() — converts to uppercase.
  • strtolower() — converts to lowercase.
  • ucfirst() — uppercases the first character.
  • str_word_count() — counts the words.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Validate that a password is at least 8 characters long before saving it.
  • Truncate a blog post excerpt to 150 characters and add an ellipsis.
  • Convert user input to uppercase for a case-insensitive username comparison.

More examples

Measuring string length

strlen() returns the byte count of a string, making it ideal for minimum-length validation.

Example · php
<?php
$password = 'secret123';

if (strlen($password) < 8) {
    echo 'Password too short.';
} else {
    echo 'Password length OK: ' . strlen($password);
}

Changing string case

strtolower(), strtoupper(), and ucwords() normalise string case for comparisons and display.

Example · php
<?php
$input = 'hello WORLD';

echo strtolower($input);  // hello world
echo strtoupper($input);  // HELLO WORLD
echo ucwords($input);     // Hello World

Trimming and padding strings

trim() strips whitespace from both ends; str_pad() is useful for fixed-width output like order IDs.

Example · php
<?php
$raw = "   hello   ";
echo trim($raw);           // 'hello'
echo ltrim($raw);          // 'hello   '
echo str_pad('42', 5, '0', STR_PAD_LEFT); // 00042

Discussion

  • Be the first to comment on this lesson.