Using PHP strlen to Get the Length of a String
This article explains how PHP's built‑in strlen function works to return the byte length of a string, demonstrates its usage with sample code, discusses the difference between byte and character counts, and highlights considerations for multibyte encodings.
PHP is a popular server‑side programming language that provides many 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, we simply call strlen and pass the target string as an argument. Below is an example.
<?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 echo to output the length.
Running the script produces the following output:
字符串"Hello World!"的长度是:12The strlen function is straightforward: pass a string and it returns the length.
It is important to note that strlen returns the number of bytes, not the number of characters. For single‑byte encodings 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 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 to ensure accurate results.
Java learning materials
C language learning materials
Frontend learning materials
C++ learning materials
PHP learning materials
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.