Using PHP strlen() to Get String Length
This article explains how the PHP strlen() function works to determine the length of a string, provides a sample code snippet that assigns a string to a variable, calculates its length, and discusses important considerations such as byte versus character counting and encoding issues.
PHP is a popular server‑side programming language that offers 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, you simply call strlen and pass the target string as an argument. Below is a sample code example:
<?php
$str = "Hello World!";
$length = strlen($str);
echo "字符串{$str}的长度是:{$length}";
?>In the code, 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 string length to the screen.
Running the above script produces the following output:
字符串"Hello World!"的长度是:12The example shows that strlen is straightforward and easy to use: simply pass a string to the function and it returns the length.
It is important to note that the function returns the number of bytes in the string, 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 you must be careful when using strlen with such strings.
In summary, strlen is a very useful function for obtaining string length. Whether you are writing a simple script or developing a complex application, it provides a powerful and convenient tool, but you should always 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.