I have used $countries = \Drupal\Core\Locale\CountryManager::getStandardList(); to render array of countries with country code as their keys. But when I debug the variable $countries; print_r($countries);die; it goes into infinite loop and result does not get rendered. It shows 404.

How to get country list array?


You get the infinite loop, because the country name is a translatable markup and print_r() can't handle this object. If you cast the country name to a string, then it is printable in php:

 $countries = \Drupal\Core\Locale\CountryManager::getStandardList();
 foreach ($countries as $key => $value) {
   $country_name = (string) $value;
   print "$key - $country_name\n";

This is not needed for rendering, because twig can handle this object. This is only for debugging.

  • How can I get list of states for a particular country?
    – ARUN
    Jun 6 '17 at 7:25

$countries = \Drupal\Core\Locale\CountryManager::getStandardList(); foreach ($countries as $key => $value) { $countries[$key] = $value->__toString(); }
$countries will return the array.


While the other answers return you the country list, the list might not be complete. The CountryManager class also provides a different function getList(). It returns the standard list that is returned by the static function getStandardList(), and allows other modules to add/alter the countries in the list.

Luckily, the CountryManager is also registered as a service and can be used as follows:

$country_manager = \Drupal::service('country_manager');
$list = $country_manager->getList();
$countries = [];
foreach ($list as $key => $value) {
  $val = $value->__toString();
  $countries[$key] = $val;
// $countries - will contain key-valued paid of country code and name.

If you are using this in the controller, or any other service, it is recommended to properly inject the service following dependency injection pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.