PHP strlen() Function

Get the length of a string in bytes

Try strlen() - edit and run
Output
13
0
10

What does strlen() do?

strlen() returns the number of bytes in a string. For plain ASCII text that equals the number of characters, but UTF-8 characters such as é or emoji use 2-4 bytes each, so strlen() reports more than the visible character count.

Syntax

strlen(string $string): int

Parameters

  • $string - The string to measure. Spaces, tabs and newlines are counted like any other byte.

Return value

The length of $string in bytes as an int. An empty string returns 0.

strlen() examples

Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.

1. Basic string length

<?php
$text = "Hello, World!";
echo strlen($text) . "\n";
echo strlen("") . "\n";
echo strlen("  padded  ") . "\n";

Output:

13
0
10

2. Bytes vs characters (UTF-8)

The é in "café" is two bytes in UTF-8. To count characters use mb_strlen() (mbstring extension) or, without mbstring, split the string with a Unicode-aware regex.

<?php
$word = "café";
echo strlen($word) . "\n";
echo count(preg_split('//u', $word, -1, PREG_SPLIT_NO_EMPTY)) . "\n";

Output:

5
4

3. Validate the length of user input

<?php
function validateUsername(string $name): string {
    $len = strlen(trim($name));
    if ($len < 3) {
        return "Too short ($len chars)";
    }
    if ($len > 16) {
        return "Too long ($len chars)";
    }
    return "OK";
}
echo validateUsername("al") . "\n";
echo validateUsername("alice_92") . "\n";
echo validateUsername("a_very_long_username_here") . "\n";

Output:

Too short (2 chars)
OK
Too long (25 chars)

Common mistakes and gotchas

  • Multibyte text: strlen("café") is 5, not 4. Use mb_strlen($s) when you need the number of characters.
  • Passing null: strlen(null) is deprecated since PHP 8.1 and emits "Passing null to parameter #1 ($string) of type string is deprecated". Use strlen($value ?? '').
  • Arrays: passing an array throws a TypeError. Use count() for arrays.
  • Checking for empty input: strlen(trim($input)) === 0 is clearer than empty($input), which also treats "0" as empty.

PHP strlen() FAQ

Does strlen() count spaces?

Yes. Every byte counts, including spaces, tabs and newlines. strlen(" a ") returns 3.

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

strlen() counts bytes; mb_strlen() counts characters in a given encoding (UTF-8 by default). They differ for any non-ASCII text.

Can I use strlen() on a number?

Yes, in the default (non-strict) mode the number is converted to a string first: strlen(12345) returns 5. With declare(strict_types=1) it throws a TypeError.