PHP – How to return character by Unicode code point value using mb_chr()?


In PHP, the mb_chr() function is used to return character by Unicode code point value. This function returns a string having 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 only two parameters: $codepoint and $encoding.

  • $codepoint− This parameter is used to convert a Unicode codepoint value. For example, 128024 for U+1F418 ELEPHANT.

  • $encoding− This parameter is the character encoding. If it is absent or null, then the internal character encoding value will be used.

Return Values

This function returns a string containing the requested character if it can be represented in the specified encoding or it returns False on failure.

Note: From PHP 8.0, nullable encoding is allowed.

Example

<pre>
   <?php
      $str = [66, 64, 0x20AC, 128024];
      foreach ($str as $str) {
         var_dump(mb_chr($str, 'UTF-8'));
         var_dump(mb_chr($str, 'ISO-8859-1'));
      }
   ?>
</pre>

Output

string(1) "B"
string(1) "B"
string(1) "@"
string(1) "@"
string(3) "€"
bool(false)
string(4) "🐘"
bool(false)

Note: PHP IntlChar::chr() function can be used to convert from PHP Unicode codepoint to character.

Updated on: 23-Aug-2021

665 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements