Is there a way to get the list of available locales in PHP?

前端 未结 7 1856
清酒与你
清酒与你 2020-12-18 20:20

In Java, you can call Locale.getAvailableLocales() to get the list of available locales.

I was expecting an equivalent from the PHP Locale class, but co

7条回答
  •  误落风尘
    2020-12-18 20:55

    This might be a slight deviation from OP, but I feel it is a common enough use-case to be mentioned here. What if you want a list of language code, as defined by ICU, instead of a list of locales ?

    List of all languages

    The solution based on ResourceBundle::getLocales(''); will get you locales. You then need to map them to language codes. But even after that the list of language is not complete.

    Here is a comparison with how to do it properly:

     $languageName) {
            $languages[] = $languageCode;
        }
    
        return $languages;
    }
    
    function languageForEndUser($language): string
    {
        return Locale::getDisplayLanguage($language, $language) . ' (' . Locale::getDisplayLanguage($language) . ')';
    }
    
    $list1 = getListFromLocales();
    $list2 = getListFromLanguages();
    
    echo 'languages in list1: ' . count($list1) . PHP_EOL;
    echo 'languages in list2: ' . count($list2) . PHP_EOL;
    echo 'languages that exists in list1, but not in list2: ' . count(array_diff($list1, $list2)) . PHP_EOL;
    echo 'languages that exists in list2, but not in list1: ' . count(array_diff($list2, $list1)) . PHP_EOL;
    
    Locale::setDefault('fr'); // Assume end-user speaks french
    
    echo 'examples of language for end-user: ' . PHP_EOL;
    echo '    - ' . languageForEndUser('en') . PHP_EOL;
    echo '    - ' . languageForEndUser('fr') . PHP_EOL;
    echo '    - ' . languageForEndUser('ko') . PHP_EOL;
    
    

    This will output something similar to:

    languages in list1: 204
    languages in list2: 620
    languages that exists in list1, but not in list2: 0
    languages that exists in list2, but not in list1: 416
    examples of language for end-user: 
        - English (anglais)
        - français (français)
        - 한국어 (coréen)
    

    where we can see that the proper way yields ~400 (!) more languages.

    You can see the code in action on https://3v4l.org/TS292

提交回复
热议问题