Get Country Code in PHP, with PHP Countries

Country information is used so frequently in modern web development. This is especially true in customer relationship managements systems and e-commerce websites.

Since we do a lot of e-commerce and CRM development here at Rapid Web Services, we developed an open source library to easily retrieve country information. The rest of this post will detail how you can use this library, PHP Countries, and what it is capable of.


To install PHP Countries, just run the following Composer command.

composer require rapidwebltd/php-countries

If you’re never used Composer, take a look at the Composer website for instructions on how to install and use it.


There are many features of PHP Countries. Here are just a few.

Retrieving Country Code

To retrieve a country code from a country name, just call the getByName method to retrieve a Country object and then access its isoCodeAlpha3 property.

$country = (new Countries)->getByName('United Kingdom');
// $country->isoCodeAlpha3 == 'GBR'
// $country->isoCodeAlpha2 == 'GB'

Retrieving Country details by Country Code

PHP Countries provides a large amount of details on countries, which can be retrieved in many ways. This information includes the country’s full name, official name, languages spoken, currencies used, and more.

One of the ways to retrieve these details is by the country’s ISO code. Both the 2 and 3 character versions are supported.

var_dump((new Countries)->getByIsoCode('GBR'));

object(RapidWeb\Countries\Country)#4869 (16) {
string(14) "United Kingdom"
string(52) "United Kingdom of Great Britain and Northern Ireland"
array(1) {
string(3) ".uk"
string(2) "GB"
string(3) "GBR"
string(3) "826"
array(1) {
string(7) "English"
array(1) {
string(3) "eng"
array(1) {
string(3) "GBP"
array(1) {
string(2) "44"
string(6) "London"
string(6) "Europe"
string(15) "Northern Europe"

Retrieving Country details for All Countries

In order to retrieve an array of Country objects for every country, just call the ‘all()’ method on the main Countries object.

foreach((new Countries)->all() as $country) {
var_dump($country->name.' - '.$country->officialName);

Additional Usage & Contributions

For more documentation and additional usage examples, see the PHP Countries GitHub page. Any contributions are most welcome!

Please take a look at some of our open source projects or read some of our blog posts about open source software.