PHP strlen() function


The strlen() function in PHP is used to calculate the length of a string, meaning it counts the number of characters in the string, including spaces and special characters.

Syntax:

strlen(string);
  • string: The input string whose length is to be determined.

Example 1: Basic Usage

<?php $string = "Hello World!"; $length = strlen($string); echo "The length of the string is: " . $length; ?>

Output:

The length of the string is: 12

Explanation: The string "Hello World!" has 12 characters, including the space and the exclamation mark.

Example 2: Counting Spaces and Special Characters

<?php $string = " PHP strlen() function! "; $length = strlen($string); echo "The length of the string is: " . $length; ?>

Output:

The length of the string is: 25

Explanation: The string contains spaces before and after the text, and strlen() counts those spaces along with the text and special characters. Hence, the total length is 25.

Example 3: Empty String

<?php $string = ""; $length = strlen($string); echo "The length of the string is: " . $length; ?>

Output:

The length of the string is: 0

Explanation: An empty string has no characters, so the length is 0.

Example 4: Special Characters

<?php $string = "Hello 🌍!"; $length = strlen($string); echo "The length of the string is: " . $length; ?>

Output:

The length of the string is: 10

Explanation: Although "Hello 🌍!" visually looks like 8 characters, strlen() counts the special emoji (🌍) as multiple bytes (depending on encoding), resulting in a total length of 10.


The strlen() function is simple but essential for tasks like validation (checking if input is the correct length) or limiting content display.