How to calculate the string length in PHP 8 using strlen and mb_strlen

Description

Calculating the length of string is one of the core competences of a developer. Developers constantly have to deal with user input. Unfortunately, computers have a limited number of CPU cycles per second, a limited amount of memory and a limited number of network bandwidth. All three factors make it paramount to know the length of data which is feeded to our programs. Sometimes we also want to know where the end of an input is.

Luckily PHP 8 offers several string functions that can help us. Most often you'll be using them when you parse string in with PHP.

Essentially there are 2 functions to count strings with variable lengths — strlen and mb_strlen. The first one simply counts the number of bytes whereas the second counts the amount of characters. This is important if you have to deal with UTF8 encoded data or generally anything that isn't included in the ASCII table.

strlen in PHP 8

strlen(string $string): int

strlen returns the number of bytes in the passed $string. If the $string is empty, the function will return 0.

Examples

echo strlen("Rubus") . ' ' . strlen("家");

The examples will output:

5 3

Because the character is the Japanese kanji for house and encoded as UTF8 charater, it has a length of 3 even though you can only see a single character.

Passing null to strlen won't throw an exception but return 0.

mb_strlen in PHP 8

mb_strlen(string $string, string|null $encoding = null): int

mb_strlen returns the number of characters for the passed $string and the optionally passed $encoding parameter. Whereas strlen counted multibyte characters as multiple characters, mb_strlen counts them as single character. Passing null to mb_strlen won't throw an exception but return 0.

Erros and warnings

If the encoding is not provided and can not provided by PHP 8 internal encoding detection algorithm, an error level of E_WARNING will be emitted.

Examples

echo mb_strlen("Rubus") . ' ' . mb_strlen("家");

The examples will output:

5 1