How to calculate the length of a string in PHP

There are two ways to calculate the length of a string in PHP, which are as follows:

The strlen function

We can use the strlen function to calculate the length of a string measured in bytes. The strlen function accepts a string argument and returns an integer. It has been available since PHP version 4.

The strlen function is used when:

  • The string only contains single-byte characters.
  • We want to know the storage size of the string.

Code example

<?php
$myString = 'Hello world';
echo strlen($myString);

Code explanation

  • Line 3: We set the $myString variable to the value Hello world.
  • Line 5: We use the strlen function to calculate the length of the string, and we print the result using the echo command.

The mb_strlen function

The mb_strlen function is part of the mbstring PHP extension. It returns the length of a string in multi-byte characters. The mb_strlen function accepts a string argument and returns an integer.

The mb_strlen function accepts a second optional argument describing the character encoding type, e.g., UTF-8. If the encoding is not provided, the internal encoding for the mbstring extension is used.

The mb_strlen function has been available since PHP version 4.06. We need to install the mbstring extension in order to use it.

The mb_strlen function is used when the string may contain multi-byte characters, and we want to know the number of characters in the string.

Code example

<?php
$myString = '€10.00';
echo mb_strlen($myString, 'UTF-8');

Code explanation

  • Line 3: We set the value of the $myString variable to €10.00, where the symbol is a multi-byte character.
  • Line 5: We use the mb_strlen function to calculate the length of the $myString variable. We print the result using the echo command.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved