Use iconv_strlen() when you need to counts characters in text using a selected character encoding in a PHP application. The examples below show the actual operation and its limitations.
What Is iconv_strlen() in PHP?
Counts characters in text using a selected character encoding. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
iconv_strlen(string $string, ?string $encoding = ...): int|false
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
echo iconv_strlen("café","UTF-8");
Output:
4
Example 2: Different Input or Behavior
<?php
echo iconv_strlen("Hello","UTF-8");
Output:
5
Practical Example: Applying the Function
<?php
$labels = ["café","Résumé"]; foreach ($labels as $label) echo iconv_strlen($label,"UTF-8") . PHP_EOL;
Output:
4
6
Important Behavior and Edge Cases
strlen() counts bytes; invalid input can make iconv_strlen() fail.
Comparison With Related Functions
| Approach | Difference |
|---|---|
iconv_strlen() | Counts characters in text using a selected character encoding. |
| Related operation | mb_strlen() counts characters with mbstring; iconv_strlen() uses iconv. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | strlen() counts bytes; invalid input can make iconv_strlen() fail. |
| Confusing this function with a related operation | mb_strlen() counts characters with mbstring; iconv_strlen() uses iconv. |
Key Takeaways
- Counts characters in text using a selected character encoding.
- strlen() counts bytes; invalid input can make iconv_strlen() fail.
- mb_strlen() counts characters with mbstring; iconv_strlen() uses iconv.
Use iconv_strlen() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.