Understanding PHP strlen() Function: Syntax, Examples, and Usage

This article explains PHP's strlen() function, covering its syntax, usage examples for measuring string length with and without surrounding spaces, important encoding considerations, and provides learning resources for further in PHP development.

php Courses
php Courses
php Courses
Understanding PHP strlen() Function: Syntax, Examples, and Usage
strlen()

is a commonly used PHP string function that returns the length of a string, counting spaces and special characters but excluding the terminating null byte.

Syntax of strlen()

int strlen ( string $string )

Here, $string represents the string whose length is to be measured.

Code Examples

Example 1: Calculate string length

$str = "Hello, world!"; // define a string
echo strlen($str); // output the length of the string

The output is:

13

Example 2: Length ignoring surrounding spaces

$str = "   Hello,   world!    "; // string with spaces
echo strlen($str); // length including spaces
echo strlen(trim($str)); // length after trimming spaces

The output is:

23
13

These examples show that strlen() is widely used for quickly counting string length, useful in scenarios such as limiting user nickname length on social platforms or product name length in e‑commerce.

Note that strlen() works correctly with UTF‑8 and ISO‑8859‑1 encoded strings; other encodings may produce inaccurate results.

When using strlen(), be aware that special characters or Chinese characters may occupy multiple bytes depending on the encoding, affecting the length calculation.

PHP Learning Recommendations

Vue3+Laravel8+Uniapp Beginner to Advanced Development Tutorial

Vue3+TP6+API Social E‑commerce System Development Course

Swoole From Beginner to Master Course

Workerman+TP6 Real‑time Chat System (Limited Offer)

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.

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