How to Use PHP strlen() to Get String Length
This article explains how PHP's built‑in strlen() function works to calculate a string's length, provides a clear example with code, discusses its byte‑based return value and the implications for multibyte characters, and offers practical guidance for using it correctly in backend development.
PHP is a popular server‑side programming language that provides many powerful built‑in functions for handling strings. Among them, the strlen function is commonly used to obtain the length of a string.
String length refers to the number of characters in a string. To get the length, we simply call strlen and pass the string as an argument. Below is an example code:
In the code we first define a variable $str and assign the string “Hello World!” to it. Then we call strlen on $str to obtain its length, store the result in $length , and finally use echo to output the length.
Running the code produces the following output:
The length of "Hello World!" is: 12From the example we can see that strlen is very simple and easy to use; just pass a string and the function returns its length.
Note that the function returns the number of bytes, not the number of characters. For ASCII or UTF‑8 strings this is fine, but for multibyte characters such as Chinese, a single character may occupy multiple bytes, so caution is required when using strlen .
In summary, strlen is a useful function for obtaining string length. Whether you are writing a simple script or developing a complex application, it is a powerful and convenient tool. Remember to consider the string’s encoding to ensure accurate results.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.