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.
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: 132. 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 bytesNote 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.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.