Skip to content

Instantly share code, notes, and snippets.

@neutronstein
Forked from IonBazan/flag.php
Created February 14, 2024 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neutronstein/b9506d07c985fd713ebf39c8ad3ed1af to your computer and use it in GitHub Desktop.
Save neutronstein/b9506d07c985fd713ebf39c8ad3ed1af 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'); // πŸ‡ΊπŸ‡Έ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment