Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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_encodingconfiguration 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 encodingsAlways specify the encoding parameter for consistent results
Returns
falseon 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.
