PHP strlen

Created with Sketch.

PHP strlen

Introduction to the PHP strlen() function

The strlen() function returns the length of a specified string. Here’s the syntax of the strlen() function:

strlen ( string $string ) : int

Code language: PHP (php)

The strlen() function has one parameter $string, which is the string to measure the length. The strlen() function returns the length of the $string in bytes or zero if the $string is empty.

It’s important to note that the strlen() function returns the number of bytes rather than the number of characters. If each character is 1 byte, the number of bytes is the same as the number of characters.

However, if you deal with the multibyte string, e.g., UTF-8, the number of bytes is higher than the number of characters.

To get the number of characters in a multibyte string, you should use the mb_strlen() function instead:

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

Code language: PHP (php)

The mb_strlen() function has an additional $encoding that specifies the character encoding of the $string.

The mb_strlen() function returns the number of characters in the $string having character $encoding. The mb_strlen() returns one for each multibyte character.

PHP strlen() function examples

Let’s take some examples of using the strlen() function.

1) Simple strlen() function example

The following example uses the strlen() function to return the length of the string PHP:

<?php
$str = 'PHP';
echo strlen($str); // 3

Code language: PHP (php)

2) Using the strlen() with a multibyte string

The following multibyte string has five characters. However, its size is 15 bytes.

'こんにちは'

Code language: PHP (php)

By the way, こんにちは is a greeting in Japanese. It means hello in English.

The strlen() function returns 15 bytes for the string 'こんにちは':

<?php

$message = 'こんにちは';
echo strlen($message); // 15 bytes

Code language: PHP (php)

Output:

15

Code language: PHP (php)

But the mb_strlen() function returns five characters for that string:

<?php

$message = 'こんにちは';
echo mb_strlen($message); // 5 characters

Code language: PHP (php)

Output:

5

Code language: PHP (php)

Summary

  • Use the PHP strlen() function to get the number of bytes of a string.
  • Use the PHP mb_strlen() function to get the number of characters in a string with a specific encoding.

Leave a Reply

Your email address will not be published. Required fields are marked *