Backend Development 3 min read

Using PHP strlen() to Get String Length

This article explains how the PHP strlen() function works, shows a complete code example that calculates and prints the length of a string, and discusses important encoding considerations such as byte versus character counts for multibyte characters.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP strlen() to Get String Length

PHP is a popular server‑side language that provides many built‑in functions for string handling, among which strlen is commonly used to obtain the length of a string.

The length refers to the number of characters (bytes) in the string. By calling strlen($str) and passing the target string as an argument, the function returns its length. The following example demonstrates this:

The script first defines $str with the value "Hello World!" , then calls strlen to compute its length, stores the result in $length , and finally outputs the length with echo .

Running the code produces:

字符串"Hello World!"的长度是:12

The strlen function is simple and convenient: it returns the number of bytes in the string. For single‑byte encodings such as ASCII or UTF‑8 this matches the character count, but for multibyte characters (e.g., Chinese) the byte count may differ, so developers should be aware of the string’s encoding when using strlen .

In summary, strlen is a useful tool for obtaining string length in PHP scripts and applications, provided the encoding considerations are taken into account.

BackendPHPTutorialstring lengthstrlen
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.