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.