PHP 8 reference · String Functions

PHP strlen() Function

Return the length of a string in bytes. Multibyte characters such as é count as several bytes; use mb_strlen() to count characters.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

strlen(string $string): int

Parameters

ParameterDescription
string The input string.

Return value

The number of bytes, as an int.

Examples

Count bytesTry it yourself
<?php
echo strlen("camel"), "\n";
echo strlen(""), "\n";
echo strlen("  hi  "), "\n"; // spaces count too

Output

5
0
6
Bytes vs charactersTry it yourself
<?php
$word = "café";
echo strlen($word), "\n";    // 5: é takes 2 bytes in UTF-8
echo mb_strlen($word), "\n"; // 4 characters

Output

5
4

Common mistakes

  • strlen() counts bytes, not characters. For user-facing UTF-8 text use mb_strlen().
  • Use count() for arrays; strlen() on an array throws a TypeError.
  • Since PHP 8.1, passing null is deprecated. Write strlen($name ?? "") when a value can be missing.

Version history

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?