Backend Development 3 min read

How to Use PHP strlen() to Measure String Length – Syntax, Examples, and Tips

This article explains the PHP strlen() function, its syntax, and provides multiple code examples for obtaining string length, checking for empty strings, validating length limits, and handling multibyte characters, while noting the need for mb_strlen() for Unicode strings.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP strlen() to Measure String Length – Syntax, Examples, and Tips

In PHP development, obtaining the length of a string is a common requirement, and the built‑in strlen() function is used for this purpose.

1. Getting the length of a string

int strlen ( string $string )

The function accepts a single string argument and returns its length in bytes.

$foo = "Hello, World!";
$length = strlen($foo);
echo "String length is: " . $length; // Output: String length is: 13

2. Checking if a string is empty

$bar = "";
if (strlen($bar) == 0) {
    echo "String is empty";
} else {
    echo "String is not empty";
}

3. Validating that a string does not exceed a certain length

$password = "abcd";
$length = strlen($password);
if ($length > 8) {
    echo "Password is too long, please re‑enter";
} else {
    echo "Password length is acceptable";
}

4. Getting the length of a multibyte (e.g., Chinese) string

$chinese = "你好,世界!";
$length = strlen($chinese);
echo "String length is: " . $length; // Output may be 15 because each Chinese character occupies multiple bytes

Note that strlen() counts bytes, not characters; for multibyte strings you should use mb_strlen() to obtain the actual character count.

Measuring string length is frequently used for input validation, string manipulation, and conditional logic. By mastering strlen() , developers can efficiently handle these tasks in PHP.

Backendstring lengthphp tutorialstrlen
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.