PHP strlen() Function

Quick summary: The PHP strlen() function returns the length of a string.

PHP strlen() Syntax

strlen(string $string): int
PHP

PHP strlen() Basic examples

echo strlen("abcdef");
PHP
Output:
6

Counts the number of characters in the string.

var_dump(strlen(""));
PHP
Output:
int(0)

An empty string has a length of 0.

PHP strlen() Real-world usage

$password = "secret123";
if (strlen($password) < 8) {
    echo "Password too short";
} else {
    echo "Password ok";
}
PHP
Output:
Password ok

Validates the minimum length of a password.

PHP strlen() Edge cases

$text = "  ";
echo strlen($text);
PHP
Output:
2

Spaces are counted as characters.

PHP strlen() Common mistakes

Using strlen with multibyte characters

strlen counts bytes, not characters. For UTF-8, use mb_strlen.

Incorrect
echo strlen("🚀"); // returns 4
Correct
echo mb_strlen("🚀"); // returns 1

Use mb_strlen for correct character counting in UTF-8 strings.

PHP strlen() Frequently Asked Questions

What does strlen() do in PHP?

strlen() returns the length of a string in bytes.

Is strlen() counting characters or bytes?

strlen() counts bytes, not characters, which can differ for multibyte encodings like UTF-8.

Why does strlen() return incorrect length for UTF-8 strings?

strlen() counts bytes, so multibyte characters are counted as multiple bytes. Use mb_strlen() for accurate character count.

What is the difference between strlen() and mb_strlen()?

strlen() counts bytes, while mb_strlen() counts characters in multibyte encodings like UTF-8.

Can strlen() return zero?

Yes, strlen() returns 0 if the string is empty.

Does strlen() ignore whitespace?

No, strlen() counts all characters including spaces, tabs, and newlines.

What happens if strlen() is used on a non-string value?

PHP may cast the value to a string or produce a warning depending on the type and PHP version.

Is strlen() fast in PHP?

Yes, strlen() is a very fast built-in function implemented in C and is efficient for most use cases.

Can strlen() be used for validation?

Yes, strlen() is often used to validate string length, such as checking minimum or maximum input size.

Does strlen() count newline characters?

Yes, strlen() counts newline and other special characters as part of the string length.

How to get the number of characters in UTF-8 string?

Use mb_strlen($string, 'UTF-8') to count characters instead of bytes.

What is a real-world use case of strlen()?

strlen() is commonly used to validate input length, enforce password rules, or check string size before processing.

PHP strlen() Related PHP Functions