PHP – How to return the character count of a string using iconv_strlen()?

In PHP, the iconv_strlen() function is used to return the character count of a given string. This function is particularly useful for multibyte character encodings where regular strlen() might give incorrect results. It was introduced in PHP 5 and the encoding parameter became nullable from PHP 8.0.

Syntax

int|false iconv_strlen(string $string, ?string $encoding = null)

Parameters

This function accepts two parameters:

  • $string − The input string to count characters from.

  • $encoding − The character encoding to use. If omitted or null, the value of iconv.internal_encoding configuration option is used.

Return Value

Returns the character count as an integer, or false if an error occurs during encoding conversion.

Example 1: Basic Usage

Here's a simple example demonstrating the basic usage of iconv_strlen()

<?php
    // UTF-8 string
    $string = "hello world!";
    $count = iconv_strlen($string, "UTF-8");
    
    echo "Character count: " . $count;
?>
Character count: 12

Example 2: Multibyte Characters

This example shows how iconv_strlen() correctly handles multibyte characters compared to strlen()

<?php
    $unicode_string = "Hello ??";
    
    echo "iconv_strlen(): " . iconv_strlen($unicode_string, "UTF-8") . "
"; echo "strlen(): " . strlen($unicode_string); ?>
iconv_strlen(): 8
strlen(): 12

Key Points

  • Use iconv_strlen() for accurate character counting in multibyte encodings

  • Always specify the encoding parameter for consistent results

  • Returns false on encoding errors, not an exception

Conclusion

The iconv_strlen() function is essential for accurate character counting in multibyte strings. Unlike strlen(), it correctly counts characters rather than bytes, making it ideal for internationalized applications.

Updated on: 2026-03-15T09:56:14+05:30

399 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements