Skip to content

Instantly share code, notes, and snippets.

@IonBazan
Created October 22, 2021 09:27
Show Gist options
  • Save IonBazan/b0d6165b2dfa1afc6329ea885e1feeb5 to your computer and use it in GitHub Desktop.
Save IonBazan/b0d6165b2dfa1afc6329ea885e1feeb5 to your computer and use it in GitHub Desktop.
Country code to country flag Emoji (PL -> πŸ‡΅πŸ‡±)
<?php
/**
* Converts country code (ISO 3166-1) to its emoji flag representation (PL -> πŸ‡΅πŸ‡±).
*
* This solution supports both lowercase and uppercase codes using modulo 32 .
* Since it doesn't perform any validation, you should make sure the code is a valid country code first.
*
* 0x1F1E5 is a code of character right before "REGIONAL INDICATOR SYMBOL LETTER A" (πŸ‡¦).
*
* Since there are 32 letters in the ASCII and A is at code 65 (dec), modulo operation returns:
* - 1 for "A" and "a"
* - 2 for "B" and "b"
* etc.
*/
function country2flag(string $countryCode): string
{
return (string) preg_replace_callback(
'/./',
static fn (array $letter) => mb_chr(ord($letter[0]) % 32 + 0x1F1E5),
$countryCode
);
}
echo country2flag('PL'); // πŸ‡΅πŸ‡±
echo country2flag('SG'); // πŸ‡ΈπŸ‡¬
echo country2flag('us'); // πŸ‡ΊπŸ‡Έ
@thesadoo
Copy link

Sweet!

@vicksparx
Copy link

Good work.

@b12e
Copy link

b12e commented Apr 3, 2024

Thanks!

I just did the same in Javascript based off this code:

function country2flag(countryCode) {
  return countryCode.replace(/./g, (letter) => String.fromCodePoint((letter.charCodeAt(0) % 32) + 0x1F1E5));
}

@chinesespy
Copy link

thanks : )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment