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 character by Unicode code point value using mb_chr()?
In PHP, the mb_chr() function is used to return a character by Unicode code point value. This function returns a string containing the character identified by the Unicode code point value, encoded in the specified encoding.
Syntax
string mb_chr(int $codepoint, string $encoding)
Parameters
mb_chr() accepts two parameters: $codepoint and $encoding.
$codepoint − The Unicode code point value to convert. For example, 128024 for U+1F418 ELEPHANT.
$encoding − The character encoding. If omitted or null, the internal character encoding value will be used.
Return Value
This function returns a string containing the requested character if it can be represented in the specified encoding, or false on failure.
Note: From PHP 8.0, nullable encoding is allowed.
Example
Here's how to convert different Unicode code points to characters using various encodings −
<?php
$codepoints = [66, 64, 0x20AC, 128024];
foreach ($codepoints as $codepoint) {
echo "Code point: $codepoint<br>";
var_dump(mb_chr($codepoint, 'UTF-8'));
var_dump(mb_chr($codepoint, 'ISO-8859-1'));
echo "<br>";
}
?>
Code point: 66 string(1) "B" string(1) "B" Code point: 64 string(1) "@" string(1) "@" Code point: 8364 string(3) "?" bool(false) Code point: 128024 string(4) "?" bool(false)
Key Points
UTF-8 encoding supports a wider range of Unicode characters than ISO-8859-1
When a character cannot be represented in the specified encoding, the function returns
falseThe Euro symbol (?) and emoji characters require UTF-8 encoding
Conclusion
The mb_chr() function is essential for converting Unicode code points to characters in PHP. Always use UTF-8 encoding for maximum character support, especially when working with international text or emoji.
