-1

I use code that handles a response from a 3rd party API and that response contains some language codes. I'd seen that there seem to be standards defining official codes for languages and was wondering if there was any way to access these in PHP.

I know also that some people just use hardcoded lists of codes, but I'd prefer to leave maintaining a list to someone else, it's not every day that a new language will be added but it does happen

My question is how can I get a list of locale and languages in PHP?

mickadoo
  • 3,337
  • 1
  • 25
  • 38

1 Answers1

0

I found that the PHP extension intl includes some classes to deal with locales, but it takes a bit of playing around to get what I wanted.

The documentation for the intl extension is here. For me installing it was as simple as running

sudo apt install php8.0-intl

Then to show how to get the different locales, codes and languages I used the following code:

$locales = ResourceBundle::getLocales('');
printf('Found %d locales like %s', count($locales), implode(',', array_slice($locales, 0, 5)));
echo PHP_EOL;

$languageCodes = array_unique(array_map(fn ($locale) => Locale::getPrimaryLanguage($locale), $locales));
printf('Found %d language codes like %s', count($languageCodes), implode(',', array_slice($languageCodes, 0, 5)));
echo PHP_EOL;

$languages = array_unique(array_map(fn ($code) => Locale::getDisplayName($code), $languageCodes));
printf('Found %d languages like %s', count($languages), implode(',', array_slice($languages, 0, 5)));
echo PHP_EOL;

Which, at the time of running, produces:

Found 751 locales like af,af_NA,af_ZA,agq,agq_CM
Found 204 language codes like af,agq,ak,am,ar
Found 204 languages like Afrikaans,Aghem,Akan,Amharic,Arabic
mickadoo
  • 3,337
  • 1
  • 25
  • 38