Backend Development 4 min read

How to Get String Length in PHP Using strlen

This article explains how to use PHP's built‑in strlen function to obtain the length of a string, demonstrates the code with a "Hello World!" example, discusses byte‑versus‑character counting, and highlights considerations for multibyte encodings.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Get String Length in PHP Using strlen

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, simply call the strlen function and pass the target string as a parameter. Below is an example:

<?php
$str = "Hello World!";
$length = strlen($str);
echo "字符串{$str}的长度是{$length}";
?>

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

Running the code produces the following output:

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

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

It is important to note that strlen returns the number of bytes in the string, not the number of characters. For byte‑counted encodings such as ASCII or UTF‑8 this works fine, but for multibyte characters (e.g., Chinese) a single character may occupy multiple bytes, so extra care is required.

In summary, strlen is a useful tool for obtaining string length in both simple scripts and complex applications. Remember to consider the string’s encoding when using strlen to ensure accurate results.

Java Learning Materials

C Language Learning Materials

Frontend Learning Materials

C++ Learning Materials

PHP Learning Materials

Backend DevelopmentPHPcoding tutorialstring 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.