How to make emojis in PHP
You might want to use emojis both in your online comments and your PHP code. The later, mostly to hander the former, although PHP handles emojis gracefully. That are the methods to make emojis in PHP?
Straight in the code
PHP supports code savec in UTF-8. And emojis are also available in that character set so it is possible to use them directly in the code.
<?php echo 'π'; ?>
This method is direct and visual. You may need an emoji encyclopedia, such as https://emojipedia.org/, or emojis.wiki, where copy-paste is a great tool to select any emoji.
Yet, this all depends on the underlying text file to be always stored as UTF-8.
Using Escape Sequences
It is possible to make emojis without relying on the UTF-8 support of the editor. PHP accepts escape sequences, which is a special format to represent long UTF-8 characters. All is in ASCII characters, so these emojis are more stable in the code. They are also no WISIWIG.
<?php // Method 1: Direct Unicode escape sequences echo "\u{1F418}"; // π elephpant ?>
Using ext/mbstring
mbstring is the PHP extension for Multi-bytes strings. It is installed on many PHP binary, as it is commonly used for UTF-8 manipulation. There is a dedicated function to create the emoji.
<?php print iconv('UTF-8', 'UCS-2BE', pack('H*', '1F418'); // π elephpant ?>
The codepoint has to be provided as an hexadecimal value, hence the 0x
prefix. In particular, the codepoint is mentionned in emoji or UTF-8 character references. It is also possible to pass the decimal or binary value of the codepoint, but it is less common.
Using iconv
The other PHP extension to convert between encodings is iconv. The first step is to pack the codepoint into a 32 big endian integer, then to convert it from UCS-4 (big endian) to UTF-8.
<?php print iconv('UCS-4BE', 'UTF-8', pack('N', 0x1f418)); // π elephpant ?>
Using html_entity_decode()
html_entity_decode() converts HTML sequences to characters. This is an alternative to using PHP escape-sequences,
<?php print html_entity_decode('&#' . 0x1F418 . ';', ENT_NOQUOTES, 'UTF-8'); // π elephpant // space between dot and 0 is important ?>
Using a ready-made PHP component
There are components that convert method calls, constants or escape sequences to emojis. This makes it easier to handle in case the emojis are dynamically managed, such as automatically added in titles or comments.
You can use emojione/emojione or spatie/emoji
<?php echo "π"; // π elephpant echo Emoji::elephant(); // π elephpant echo Emoji::CHARACTER_ELEPHANT; // π elephpant ?>
Five ways to make emojis in PHP
These are at least five ways to make emojis in PHP. Also, they may be used in PHP code itself, not just for string manipulations. This may be applicable for mathematical functions (function β(…$numbers)) or localisation (class εεManager). A lot of fun!