How to Find String Length in PHP
Finding the length of a string is a fundamental task in PHP web
development. This article explains how to quickly determine string
length using PHP’s built-in functions, specifically focusing on
strlen() for standard ASCII strings and
mb_strlen() for multibyte character sets like UTF-8. You
will learn how to choose the right function for your data and see
practical code examples for both.
The Standard Method:
strlen()
The most common way to find the length of a string in PHP is by using
the built-in strlen() function. This function accepts a
string as its argument and returns the number of bytes it contains.
Syntax
strlen(string $string): intExample
<?php
$string = "Hello, World!";
$length = strlen($string);
echo $length; // Outputs: 13
?>The Multibyte Method:
mb_strlen()
While strlen() works perfectly for standard English
text, it can produce inaccurate results when dealing with special
characters, accented letters, emojis, or non-Latin alphabets (such as
Chinese, Arabic, or Cyrillic).
Because strlen() measures bytes rather
than actual characters, a multibyte character (which can take up to 4
bytes in UTF-8) will be counted multiple times. To get the accurate
character count, you should use the
mb_strlen() function.
Syntax
mb_strlen(string $string, ?string $encoding = null): intExample Comparison
<?php
$string = "Café";
// strlen counts bytes (é takes 2 bytes in UTF-8)
echo strlen($string); // Outputs: 5
// mb_strlen counts actual characters
echo mb_strlen($string); // Outputs: 4
?>Which Function Should You Use?
- Use
strlen()if you are certain the input contains only standard single-byte English characters (ASCII) or when you specifically need to measure the data size in bytes. - Use
mb_strlen()when working with user input, databases, or multilingual applications where UTF-8 characters are expected.