Skip to content

Core\Str::fromCodePoint

Core\Str::fromCodePoint(uint $codePoint): stringCore\Str::fromCodePoint(
    uint $codePoint,
): string

Builds a string of one symbol from its Unicode number.

Every symbol in Unicode has a number, called its code point. Core\Str::fromCodePoint takes that number as a uint and returns a string that contains the symbol. 72 gives "H", 233 gives "é" and 8364 gives "€".

Not every number is a code point. The largest one is 0x10FFFF. The numbers from 0xD800 to 0xDFFF are reserved, and Unicode gives them no symbol. For these numbers the method throws a RuntimeError.

Core\Str::codePoints does the opposite and returns the numbers of a string. To build a string from many numbers at once, use Core\Str::fromCodePoints.

The examples below build a few symbols from their numbers, catch the error for a number that is not a code point, and turn a country code into its flag.

Parameters

  • $codePointuintThe number of the symbol. It is at most 0x10FFFF and is not in the surrogate range 0xD800 to 0xDFFF.

Return value

Returns string. A string that contains that one code point. 0x20AC gives "€".

Errors

  • RuntimeError$codePoint is above 0x10FFFF, or it is in the surrogate range 0xD800 to 0xDFFF. Unicode gives no symbol to these numbers.

Examples

Symbols from numbers

<?nvs
// Shows how to build a symbol from its Unicode number.
// This prints `H`, `é`, `€` and `😀`, one on each line.
array<uint> $numbers = [72, 233, 8364, 0x1F600];
foreach ($numbers as uint $number) {
echo Core\Str::fromCodePoint($number), "\n";
}
Output
H
é
€
😀

A number that is not a code point

<?nvs
// Shows what happens when a number is not a code point.
// 0xD800 is in the reserved range, and 0x110000 is larger than the largest code point.
// `Core\Str::fromCodePoint` throws a `RuntimeError` for both.
array<uint> $numbers = [0x41, 0xD800, 0x110000];
// This prints `65: A`, then `55296: not a code point` and `1114112: not a code point`.
foreach ($numbers as uint $number) {
string $result = '';
try {
$result = Core\Str::fromCodePoint($number);
} catch (RuntimeError $error) {
$result = 'not a code point';
}
echo $number, ': ', $result, "\n";
}
Output
65: A
55296: not a code point
1114112: not a code point

A flag from a country code

<?nvs
// Shows how to turn a two-letter country code into its flag, for example in a list of shipping countries.
// A flag is two special letters. The special "A" is code point 0x1F1E6, and "B" is the next number.
// "A" is 65, so each letter of the code moves by the same distance.
class Country
{
public static function flag(string $code): string
{
string $result = '';
foreach (Core\Str::codePoints($code) as uint $letter) {
$result = $result . Core\Str::fromCodePoint(0x1F1E6 + $letter - 65);
}
return $result;
}
}
// This prints `DE 🇩🇪`, `FR 🇫🇷` and `JP 🇯🇵`.
array<string> $countries = ['DE', 'FR', 'JP'];
foreach ($countries as string $code) {
echo $code, ' ', Country::flag($code), "\n";
}
Output
DE 🇩🇪
FR 🇫🇷
JP 🇯🇵