Skip to content

PHP Tutorial Strings

String Length

Lesson 61 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

To find out how long a string is, use strlen().

index.php
PHP
<?php
$password = "secret123";

echo strlen($password);
Output
OUTPUT
9

Spaces and punctuation count too.

index.php
PHP
<?php
echo strlen("Hello, world!");
Output
OUTPUT
13

Use it to validate input

index.php
PHP
<?php
$username = "al";

if (strlen($username) < 3) {
    echo "Username must be at least 3 characters.";
}
Output
OUTPUT
Username must be at least 3 characters.

strlen counts bytes

strlen() counts bytes, not characters. For English letters, they are the same. For characters outside basic English, they are not.

index.php
PHP
<?php
echo strlen("naive") . "\n";
echo strlen("naïve") . "\n";
echo mb_strlen("naïve");
Output
OUTPUT
5
6
5

mb_strlen() counts real characters. Use it whenever the text could contain accents, Hindi, emoji or other non-English characters. See Multibyte Strings.

Count words

index.php
PHP
<?php
$text = "PHP is easy to learn";

echo str_word_count($text);
Output
OUTPUT
5

str_word_count() is fine for English text. For other languages, split the text yourself.

Empty strings

index.php
PHP
<?php
var_dump(strlen("") === 0);
var_dump("" === "");
Output
OUTPUT
bool(true)
bool(true)
warning
Do not use strlen() to check for a missing value
A value of null or a missing variable is not an empty string. Check with isset() first, then with === "" or strlen().

Exercise: a tweet counter

Print how many characters are left in a 100-character limit for the text "Learning PHP step by step".

Show a possible solution
index.php
PHP
<?php
$text = "Learning PHP step by step";
$limit = 100;

echo "Characters left: " . ($limit - mb_strlen($text));
Output
OUTPUT
Characters left: 75