PHP strlen: A Practical Guide to String Byte Length

    Learn how PHP’s strlen measures bytes rather than characters, how encoding and type handling affect length checks, and when to use character or grapheme-cluster functions instead. This guide covers binary safety, performance, multilingual input validation, safe truncation, and essential boundary tests.

    1. Start by Defining What “Length” Means

    In PHP string processing, strlen is one of the most fundamental built-in functions. It does not answer “How many characters does this text contain?” Instead, it answers “How many bytes does this string contain?”

    That distinction affects input validation, storage limits, protocol handling, and text display. The same Chinese text can occupy different numbers of bytes depending on its encoding. A symbol that appears to be a single unit on screen may also consist of multiple encoded components. Unless the application first defines what length means, a technically correct function call can still produce the wrong business decision.

    There are three common measures:

    1. Byte length: The number of bytes in a string. This is appropriate for binary data, transmission limits, and fields explicitly measured in bytes.
    2. Character length: The number of characters counted according to a specified encoding. This is appropriate for general multilingual text validation.
    3. User-perceived length: The number of grapheme clusters, which more closely matches the text units or symbols users see. This is useful for editors, display names, and display-oriented truncation.

    strlen handles the first measure. Use it when the requirement is explicitly defined in bytes.

    2. Function Definition and Basic Behavior

    The modern function signature is:

    1. strlen(string $string): int

    The $string parameter is the string to measure. The return value is a nonnegative integer.

    1. <?php
    2. echo strlen('hello'); // 5
    3. echo strlen(''); // 0
    4. echo strlen('0'); // 1

    The string '0' is not an empty string. To check whether a string is empty, use a strict comparison:

    1. <?php
    2. $text = '0';
    3. if ($text === '') {
    4. echo 'The string is empty';
    5. } else {
    6. echo 'The string is not empty';
    7. }

    Do not substitute a general “empty value” check for an empty-string check. Some checks also treat '0' as empty, which can incorrectly reject valid input.

    strlen does not automatically remove spaces, line breaks, or other invisible content.

    1. <?php
    2. echo strlen(' a '); // 3
    3. echo strlen("\n"); // 1
    4. echo strlen("\r\n"); // 2

    “No visible text” and “zero bytes” are therefore different conditions. Whether leading or trailing whitespace should be removed is an application rule, not something the length function handles implicitly.

    3. Why strlen Cannot Directly Count Chinese Characters

    At runtime, a PHP string is a sequence of bytes. strlen counts those bytes without identifying their character encoding.

    Consider this UTF-8 string:

    1. <?php
    2. $text = '中文A';
    3. echo strlen($text); // 7
    4. echo mb_strlen($text, 'UTF-8'); // 3

    Each of the two Chinese characters occupies three bytes, while A occupies one byte. The string therefore contains seven bytes but three characters.

    This does not mean that every non-English character occupies three bytes. UTF-8 characters can occupy one to four bytes, depending on the character. Mixing different characters changes the total byte length accordingly.

    The following approach is unreliable:

    1. <?php
    2. // Incorrect: a fixed divisor cannot determine the character count.
    3. $count = strlen($text) / 3;

    Even if the current test data contains only Chinese text, this calculation will not correctly handle English letters, digits, punctuation, and other characters.

    Choose the measurement that matches the requirement:

    • To limit a request field to a maximum number of bytes, use strlen.
    • To limit text to a maximum number of characters, use a character-counting function that supports an explicit encoding.
    • To limit the number of text units or symbols users perceive, consider grapheme-cluster counting.

    These rules can coexist. A field might require both “no more than 100 characters” and “no more than 400 bytes after encoding.” Validate each condition separately; neither is a substitute for the other.

    4. Character Count Is Not Always User-Perceived Length

    mb_strlen addresses common multibyte character-counting requirements, but its result does not always match the number of text units a user perceives.

    For example, a letter followed by a combining mark may appear as one unit on screen while consisting of multiple characters. Some complex symbols are also displayed from sequences of multiple characters.

    Keep these measures distinct:

    • Byte count: Measures the underlying byte sequence.
    • Encoded character count: Measures characters according to the encoding.
    • Grapheme-cluster count: Measures text units typically perceived as a whole.

    For requirements closer to the visual reading experience, use grapheme-cluster support such as grapheme_strlen. Before doing so, verify that the required extension is enabled and define an explicit error path for input that cannot be processed correctly.

    Grapheme-cluster count is not the same as display width, either. The space a text unit occupies in a terminal or interface can depend on fonts, layout, and the display environment.

    5. Type Handling: Not All Non-String Inputs Behave Alike

    Although strlen declares a string parameter, its actual behavior also depends on the type-checking mode and runtime version. Compatibility discussions must distinguish integers, booleans, arrays, objects, and null rather than claiming that every non-string input produces the same warning.

    Scalar Conversion in Coercive Mode

    In a calling context that permits scalar coercion, some scalar values can be converted to strings before their length is measured:

    1. <?php
    2. echo strlen(12345); // Typically 5
    3. echo strlen(true); // Typically 1
    4. echo strlen(false); // Typically 0

    Although this behavior may be allowed, it should not define an input contract. A successful call does not necessarily mean the input meets the application’s requirements.

    For example, false becomes an empty string, which can make it indistinguishable from an explicitly submitted empty text value.

    Strict Typing

    With strict typing enabled, do not rely on integers or booleans being converted automatically:

    1. <?php
    2. declare(strict_types=1);
    3. echo strlen(12345); // Throws TypeError

    If the application permits a numeric value to become text, make the conversion explicit after confirming that the conversion is meaningful:

    1. <?php
    2. declare(strict_types=1);
    3. $value = 12345;
    4. $text = (string) $value;
    5. echo strlen($text); // 5

    Arrays and Objects

    An array is not a string. In modern PHP versions, passing an array to strlen produces a type error. The function does not automatically concatenate array contents and count the result.

    Some objects support string conversion, but whether objects are acceptable application inputs should be determined by the interface design. Explicitly requiring strings for text fields is usually easier to maintain and troubleshoot.

    Changes in null Handling

    Starting with PHP 8.1, passing null to a non-nullable built-in string parameter in coercive mode produces a deprecation notice. This does not mean that every non-string argument has become prohibited, nor does it mean that arrays produce only a deprecation notice.

    In strict mode, null is not a valid string argument.

    Define the intended behavior before calling the function:

    1. <?php
    2. $value = null;
    3. // Do this only if the application treats null as an empty string.
    4. $text = $value ?? '';
    5. echo strlen($text); // 0

    If null means “the field was not provided” while an empty string means “the field was explicitly left empty,” do not merge those states automatically.

    6. History and Performance: Avoid Misleading Claims

    strlen has existed across many major PHP versions, but historical error handling differs from modern behavior. When maintaining older systems, check the behavior of the target version. Do not generalize one version’s treatment of arrays or null to every input type.

    Another potentially misleading claim is that a particular internal refactoring changed strlen from O(n) to O(1).

    PHP’s runtime string representation stores length information, and older versions also had mechanisms for storing string length. It is therefore inaccurate to assume that earlier implementations had to scan every string from beginning to end on every call.

    For an existing string, reading its stored length can generally be treated as an O(1) operation. However, distinguish the length lookup from work performed before the call:

    1. <?php
    2. $length = strlen($prefix . $body . $suffix);

    The length lookup itself is usually inexpensive, but the concatenation expression may require memory allocation and byte copying. Type conversion can also introduce additional work.

    Performance analysis should cover the entire data-processing operation, not just the complexity of strlen.

    7. Binary Safety: Null Bytes Are Part of the String

    strlen counts embedded null bytes. It does not stop when it encounters \0.

    1. <?php
    2. $data = "A\0B";
    3. echo strlen($data); // 3

    This makes it suitable for measuring binary fragments, message payloads, and raw byte buffers.

    However, its result is only the byte length of the current string. It is not necessarily:

    • The total size of a file.
    • Total network traffic generated during transmission.
    • The length after encryption or compression.
    • The full storage footprint of a database record.
    • The complete memory footprint of a runtime object.

    Use the string’s length as the relevant byte measurement only when the string fully represents the data being measured.

    8. Input Validation: Check Both Characters and Bytes

    For multilingual text, a useful validation sequence is: type, encoding, character count, then byte count.

    1. <?php
    2. declare(strict_types=1);
    3. function validateText(mixed $value): array
    4. {
    5. if (!is_string($value)) {
    6. return [false, 'Input must be a string'];
    7. }
    8. if (!mb_check_encoding($value, 'UTF-8')) {
    9. return [false, 'Input must be valid UTF-8 text'];
    10. }
    11. $characters = mb_strlen($value, 'UTF-8');
    12. if ($characters < 1 || $characters > 100) {
    13. return [false, 'Character count must be between 1 and 100'];
    14. }
    15. if (strlen($value) > 400) {
    16. return [false, 'Text must not exceed 400 bytes'];
    17. }
    18. return [true, 'Validation passed'];
    19. }

    The limits of 100 characters and 400 bytes are example application requirements, not fixed function parameters or universal standards. Set actual limits according to field specifications, storage design, and interaction requirements.

    This code also depends on the multibyte string extension. Verify its availability before deployment rather than assuming that every runtime matches the development environment.

    If the application allows trimming leading or trailing whitespace, explicitly decide whether trimming happens before or after validation. The order can change the result, especially when handling signature verification, audit records, or input that must be preserved exactly.

    9. Text Truncation Requires More Than a Length Check

    Knowing a string’s byte length does not mean it is safe to cut the text at an arbitrary byte offset.

    1. <?php
    2. $text = '中文内容';
    3. // Byte-based truncation may split a UTF-8 character.
    4. $part = substr($text, 0, 4);

    If the cut falls inside a multibyte character, the result may no longer be valid UTF-8.

    Match the truncation method to the limit:

    • Truncate by character count: Use an encoding-aware substring function such as mb_substr.
    • Truncate to a byte limit while preserving complete characters: Consider mb_strcut.
    • Truncate by user-perceived text units: Use the corresponding grapheme-cluster substring functionality.

    If an ellipsis is appended after truncation, include it in the final length limit. For a byte limit, account for the appended content’s byte length. For a character limit, count it using the same character-counting rules.

    10. Essential Boundary Tests

    Tests for strlen should cover more than English text. At minimum, include the following cases:

    Input Main validation goal
    Empty string The result is 0
    String '0' It is not mistaken for an empty string
    English letters and digits Basic byte counting
    Mixed Chinese and English text The difference between byte count and character count
    Spaces and line breaks Invisible content still contributes to length
    String containing null bytes Complete binary byte counting
    Invalid encoded byte sequences Byte counting is separate from text validity
    Arrays, booleans, integers, and null Type policy and error handling
    Combining character sequences The difference between character count and user-perceived length
    Text near length limits Boundary values, truncation, and appended content

    When upgrading PHP, also check whether existing code depends on implicit conversions, deprecated behavior, or return values after warnings. Replacing those dependencies with explicit input validation is more reliable than relying on historical compatibility behavior.

    Conclusion

    The responsibility of strlen is precise: it returns the byte length of the current string. It does not identify the encoding, validate text, or determine how many letters or symbols a user sees.

    Reliable string handling starts by choosing the measurement unit, then selecting the appropriate function. Define accepted input types before checking encoding and length, and establish the truncation goal before choosing how to cut text.

    By keeping bytes, characters, and grapheme clusters separate, you can use strlen accurately for text validation, binary processing, and interface boundary checks.