Backend Development 4 min read

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

This article explains PHP's strlen() function, detailing its syntax, demonstrating how to calculate string lengths with and without spaces, and highlighting important considerations such as encoding support and special characters in various applications.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP strlen(): Syntax, Examples, and Usage

The strlen() function is a commonly used string handling function in PHP that returns the length of a string, counting spaces and special characters but excluding the null character.

Its syntax is:

int strlen ( string $string )

Here $string represents the string whose length you want to measure.

Example 1: Calculating the length of a string

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

The output is:

13

Example 2: Ignoring spaces when calculating the length

$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

From these examples, you can see that strlen() is a versatile function useful for tasks such as limiting username lengths on social platforms or product name lengths in e‑commerce applications.

Note that strlen() only reliably handles strings encoded in UTF‑8 or ISO‑8859‑1; other encodings may produce incorrect results.

When using strlen() , also be aware of special or Chinese characters, as their byte size varies with encoding and can affect the length calculation.

Java learning material download

C language learning material download

Frontend learning material download

C++ learning material download

PHP learning material download

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