Using PHP strlen() to Get String Length

This article explains how the PHP strlen() function works, shows a complete code example that calculates and prints the length of a string, and discusses important encoding considerations such as byte versus character counts for multibyte characters.

php Courses
php Courses
php Courses
Using PHP strlen() to Get String Length

PHP is a popular server‑side language that provides many built‑in functions for string handling, among which strlen is commonly used to obtain the length of a string.

The length refers to the number of characters (bytes) in the string. By calling strlen($str) and passing the target string as an argument, the function returns its length. The following example demonstrates this:

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

The script first defines $str with the value "Hello World!", then calls strlen to compute its length, stores the result in $length, and finally outputs the length with echo.

Running the code produces:

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

The strlen function is simple and convenient: it returns the number of bytes in the string. For single‑byte encodings such as ASCII or UTF‑8 this matches the character count, but for multibyte characters (e.g., Chinese) the byte count may differ, so developers should be aware of the string’s encoding when using strlen.

In summary, strlen is a useful tool for obtaining string length in PHP scripts and applications, provided the encoding considerations are taken into account.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Tutorialstrlenstring-length
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

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.