Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP strlen() function

Reference for PHP strlen(): count the bytes in a string, why UTF-8 characters can count as several bytes, empty strings, and when to use mb_strlen() instead.

strlen() returns the number of bytes in a string. For plain ASCII text that equals the number of characters, but PHP strings are byte sequences with no built-in encoding, so a character such as รฉ or ๆ—ฅ that takes several bytes in UTF-8 counts as several.

When you need the number of characters (what a user would count), use mb_strlen().

PHP
<?php
echo strlen("Hello");    // 5
echo strlen("");         // 0

Try it

PHP Bytes versus characters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Validation and special values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
strlen(string $string): int
Name Description
$string The string to measure.

Return value: the length in bytes, as an integer. An empty string gives 0.

Errors: a TypeError is thrown for arrays and objects without __toString(). Passing null is deprecated since PHP 8.1 (it still returns 0). Under declare(strict_types=1), passing an int or float throws.

Usage notes

  • Bytes, not characters. In UTF-8, ASCII letters take 1 byte, most accented Latin letters 2, most CJK characters 3 and emoji 4. Use mb_strlen() for characters.
  • Database limits. VARCHAR(255) limits are in characters in MySQL, so validate with mb_strlen() there; strlen() is the right choice for byte limits such as upload sizes or binary data.
  • Constant time. PHP stores the length with the string, so strlen() does not scan it and is safe to call in loop conditions. The compiler can even inline it.
  • Not for arrays. Use count() for arrays.
  • Passing null raises a deprecation notice in PHP 8.1+; cast or check first.
  • Whole-value checks. Use $s === "" or strlen($s) === 0 for emptiness; empty("0") is true, which surprises people.
  • Grapheme clusters. Even mb_strlen() counts code points, so a flag emoji or letter with a combining accent can still count as more than one.