DEV Community

Cover image for Country codes and regional differences
Stiven Llupa
Stiven Llupa

Posted on

Country codes and regional differences

Here's a little-known Symfony trick for apps that need to support Kosovo as a country.

Kosovo uses the code XK, but that's not an official ISO 3166 code. It is what is called a user-assigned code, meaning Symfony Intl component doesn't include it by default.

So when you call Countries::getNames() from the Symfony Intl component, Kosovo simply won't appear.

use Symfony\Component\Intl\Countries;

$countries = Countries::getNames();

isset($countries['XK']); // false

Countries::getName('XK'); // Throws MissingResourceException
Enter fullscreen mode Exit fullscreen mode

The fix? Just set this environment variable in your .env file:

# .env

SYMFONY_INTL_WITH_USER_ASSIGNED=true
Enter fullscreen mode Exit fullscreen mode

That's it. Symfony will now also recognize XK, XKK, and numeric code 983 for Kosovo.

use Symfony\Component\Intl\Countries;

Countries::getName('XK'); // 'Kosovo'

Countries::getAlpha2Code('XKK') // XK
Countries::getAlpha3Code('XK') // XKK  
Countries::getNumericCode('XK') // 983
Enter fullscreen mode Exit fullscreen mode

A one-liner that saves you from building a workaround. Super useful if you're building apps for any region that needs user-assigned country codes.

Top comments (0)