Backend Development 4 min read

How to Use PHP strlen() to Get String Length

This article explains how the PHP strlen() function works to determine the length of a string, provides a clear example with code, discusses the difference between byte and character counts, and highlights important considerations regarding character encoding when using strlen in backend development.

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

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

String length refers to the number of characters in a string. To get the length, we simply call the strlen function and pass the string to be examined as its argument. Below is an example code:

<?php
$str = "Hello World!";
$length = strlen($str);
echo "字符串"{$str}的长度是:{$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 obtain the length of $str and store the result in the variable $length . Finally, we use an echo statement to output the string’s length to the screen.

Running the above code produces the following result:

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

From the example we can see that the strlen function is very simple and easy to use. Passing a string as the argument returns its length.

It is important to note that this function returns the number of bytes in the string, not the number of characters. For byte‑counted strings such as ASCII or UTF‑8, this is fine, but for multibyte characters (e.g., Chinese), a single character may occupy multiple bytes, so strlen must be used with caution.

In summary, the strlen function is a very useful tool for obtaining a string’s length. Whether writing a simple script or developing a complex application, it is a powerful and convenient utility. Remember to consider the string’s encoding when using strlen to ensure accurate results.

PHP Quick Learning Tutorial (Beginner to Advanced)

Scan QR code to receive free learning materials

backendPHPcodingstring 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.