Backend Development 3 min read

How to Use PHP's strlen() Function to Get String Length

This article explains PHP's built‑in strlen() function, demonstrates its usage with a complete code example, discusses the output, and highlights important considerations about byte‑based length versus character count for multibyte strings.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP's strlen() Function to Get String Length

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

String length refers to the number of characters in the string. To get the length, simply call strlen and pass the target string as an argument. The following example illustrates this:

<?php $str = "Hello World!"; $length = strlen($str); echo "The length of \"$str\" is: $length"; ?>

In the code above, we first define a variable $str and assign the string "Hello World!" to it. Then we call the strlen function to retrieve the length of $str and store the result in the variable $length . Finally, we use echo to output the length to the screen.

Running this script produces the output:

The length of "Hello World!" is: 12

The strlen function is straightforward and easy to use: provide a string as the argument and the function returns its length. However, it returns the number of bytes, not the number of characters. For single‑byte encodings such as ASCII or UTF‑8, this is usually fine, but for multibyte characters (e.g., Chinese characters) a single character may occupy multiple bytes, so strlen may give unexpected results.

In summary, strlen is a useful function for obtaining string length in PHP, but developers should be aware of the string’s encoding and consider multibyte‑safe alternatives when necessary.

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.