PHP Country Manager Class
The PHP Country Manager class is a versatile utility designed to manage country-related data effectively. It simplifies the process of working with country information, such as generating dropdowns, filtering countries, and retrieving specific details. This class is particularly useful for applications that require geographical data management.
Features of the Country Manager Class
- Generate Dropdown: Create dynamic countries, phone codes, and currencies.
- Check Country Code: Verify if a specific country code exists in the dataset.
- Get Country Details: Retrieve detailed information about a country using its code.
- Filter by Continent: Get a list of countries belonging to a specific continent.
- Search by Name: Find a country by its name (case-insensitive).
- Filter by Currency: Retrieve all countries that use a specific currency.
- Filter by Phone Code: Get countries associated with a particular phone code.
- List All Continents: Extract a unique list of all continents in the dataset.
- Country Flags: Retrieve country flags in PNG, SVG, JPEG, and WebP formats, available in various sizes.
- Coat Of Arms: Access country coat of arms images in PNG and SVG formats.
PHP Country And Details
PHP country and other details code. click to download all code
<?php
$country_list = [
"AF" => [
"name" => "Afghanistan",
"phone" => 93,
"alpha_3" => "AFG",
"continent" => "Asia",
"continent_code" => "AS",
"capital" => "Kabul",
"currency_code" => "AFN",
"currency_symbol" => "؋",
"currency_name" => "Afghan afghani"
],
"AX" => [ "name" => "Åland Islands", "phone" => 358, "alpha_3" => "ALA", "continent" => "Europe", "continent_code" => "EU", "capital" => "Mariehamn", "currency_code" => "EUR", "currency_symbol" => "€", "currency_name" => "Euro" ],
"AL" => [ "name" => "Albania", "phone" => 355, "alpha_3" => "ALB", "continent" => "Europe", "continent_code" => "EU", "capital" => "Tirana", "currency_code" => "ALL", "currency_symbol" => "Lek", "currency_name" => "Albanian lek" ],
//...
"ZW" => [ "name" => "Zimbabwe", "phone" => 263, "alpha_3" => "ZWE", "continent" => "Africa", "continent_code" => "AF", "capital" => "Harare", "currency_code" => "ZWL", "currency_symbol" => "$", "currency_name" => "Zimbabwean dollar" ]
];
PHP Code Example
Below is the PHP code for the Country Manager class. You can use this code in your project to handle country-related data efficiently.
<?php
/**
* CountryManager - A comprehensive class for managing country-related data and operations
*/
class CountryManager {
private $countries = [];
public function __construct(array $country_list) {
$this->countries = $country_list;
}
/**
* Generate HTML dropdown with customizable attributes
* @param string $type Type of dropdown (country|phone|currency)
* @param array $attributes HTML attributes for the select element
* @param string|null $selected Selected value
* @return string HTML select element
*/
public function generateDropdown(string $type, array $attributes = [], ?string $selected = null): string {
$attributesStr = '';
if (is_array($attributes)) {
foreach ($attributes as $key => $value) {
$attributesStr .= " {$key}=\"" . htmlspecialchars($value, ENT_QUOTES) . "\"";
}
}
$select = "<select{$attributesStr}>";
switch (strtolower($type)) {
case 'country':
$select .= $this->getCountryDropdown($selected);
break;
case 'phone':
$select .= $this->getPhoneCodeDropdown($selected);
break;
case 'currency':
$select .= $this->getCurrenciesDropdown($selected);
break;
case 'continent':
$select .= $this->getContinentsDropdown($selected);
break;
}
return $select . '</select>';
}
/**
* Generate HTML dropdown of countries
* @param string|null $selected Selected country code
* @return string HTML select element
*/
public function getCountryDropdown(?string $selected = null): string {
$options = '<option value="" >Select a country</option>';
foreach ($this->countries as $code => $country) {
$isSelected = ($selected === $code) ? ' selected' : '';
$options .= "<option value=\"{$code}\"{$isSelected}>{$country['name']}</option>";
}
return $options;
}
/**
* Generate HTML dropdown of countries
* @param string|null $selected Selected country code
* @return string HTML select element
*/
public function getPhoneCodeDropdown(?string $selected = null): string {
$options = '<option value="">Phone</option>';
foreach ($this->countries as $code => $country) {
$isSelected = ($selected === $code) ? ' selected' : '';
$options .= "<option value=\"{$country['phone']}\"{$isSelected}>{$country['name']} (+{$country['phone']})</option>";
}
return $options;
}
/**
* Generate HTML dropdown of countries
* @param string|null $selected Selected currency code
* @return string HTML select element
*/
public function getCurrenciesDropdown(?string $selected = null): string {
$currencyList = $this->getAllCurrencies();
$options = '<option value="">Currency</option>';
foreach ($currencyList as $code => $currency) {
$isSelected = ($selected === $code) ? ' selected' : '';
$options .= "<option value=\"{$code}\"{$isSelected}>{$currency['name']}</option>";
}
return $options;
}
/**
* Generate HTML dropdown of continents
* @param string|null $selected Selected continent code
* @return string HTML select element
*/
public function getContinentsDropdown(?string $selected = null): string {
$continentList = $this->getContinents();
$options = '<option value="">Continent</option>';
foreach ($continentList as $code => $name) {
$isSelected = ($selected === $code) ? ' selected' : '';
$options .= "<option value=\"{$code}\"{$isSelected}>{$name}</option>";
}
return $options;
}
/**
* Get all available continents
* @return array List of continents
*/
public function getContinents(): array {
return [
'AF' => 'Africa',
'AN' => 'Antarctica',
'AS' => 'Asia',
'EU' => 'Europe',
'OC' => 'Australia',
'NA' => 'North America',
'SA' => 'South America'
];
}
/**
* Check if country code exists
* @param string $code Country code to check
* @return bool
*/
public function isValidCountryCode(string $code=''): bool {
return isset($this->countries[strtoupper($code)]);
}
/**
* Get country details by country code
* @param string $code Country code
* @return array|null Country details or null if not found
*/
public function getCountryByCode(string $code=''): ?array {
if (empty($code)) {
return null;
}
$code = strtoupper($code);
return $this->countries[$code] ?? null;
}
/**
* Get countries by continent
* @param string $continent Continent name
* @return array Countries in the specified continent
*/
public function getCountriesByContinent(string $continent=''): array {
if (empty($continent)) {
return null;
}
return array_filter($this->countries, function ($country) use ($continent) {
return strcasecmp($country['continent'], $continent) === 0;
});
}
/**
* Get country name by code
* @param string $code Country code
* @return string|null Country name or null if not found
*/
public function getCountryName(string $code=''): ?string {
return $this->countries[strtoupper($code)]['name'] ?? null;
}
/**
* Get phone code by country code
* @param string $code Country code
* @return int|null Phone code or null if not found
*/
public function getPhoneCode(string $code=''): ?int {
return $this->countries[strtoupper($code)]['phone'] ?? null;
}
/**
* Get capital by country code
* @param string $code Country code
* @return string|null Capital city or null if not found
*/
public function getCapital(string $code=''): ?string {
return $this->countries[strtoupper($code)]['capital'] ?? null;
}
/**
* Get country by capital name
* @param string $capital Capital name
* @return array|null Country details or null if not found
*/
public function getCountryByCapital(string $capital=''): ?array {
if (empty($capital)) {
return null;
}
foreach ($this->countries as $country) {
if (strcasecmp($country['capital'], $capital) === 0) {
return $country;
}
}
return null;
}
/**
* Count countries by continent
* @return array Continent name as key and country count as value
*/
public function countCountriesByContinent(): array {
$continentCounts = [];
foreach ($this->countries as $country) {
$continent = $country['continent'];
if (!isset($continentCounts[$continent])) {
$continentCounts[$continent] = 0;
}
$continentCounts[$continent]++;
}
return $continentCounts;
}
/**
* Search countries by name
* @param string $query Search query
* @return array Matching countries
*/
public function searchCountries(string $query=''): array {
if (empty($query)) {
return [];
}
$query = strtolower($query);
return array_filter($this->countries, function ($country) use ($query) {
return strpos(strtolower($country['name']), $query) !== false;
});
}
/**
* Get countries by currency code
* @param string $currency Currency code
* @return array Countries using the specified currency
*/
public function getCountriesByCurrency(string $currency_code=''): array {
if (empty($currency_code)) {
return [];
}
$currency_code = strtoupper($currency_code);
return array_filter($this->countries, function ($country) use ($currency_code) {
return $country['currency_code'] === $currency_code;
});
}
/**
* Get all available currencies with countries
* @return array Currencies with their corresponding countries
*/
public function getAllCurrencies(): array {
$currencies = [];
foreach ($this->countries as $code => $country) {
if (!isset($currencies[$country['currency_code']])) {
$currencies[$country['currency_code']] = [
'symbol' => $country['currency_symbol'],
'name' => $country['currency_name'],
'countries' => []
];
}
$currencies[$country['currency_code']]['countries'][] = [
'code' => $code,
'name' => $country['name']
];
}
// Sort by currency name
uasort($currencies, function($a, $b) {
return strcasecmp($a['name'], $b['name']);
});
return $currencies;
}
/**
* Get neighboring countries that share the same continent
* @param string $code Country code
* @return array Countries in the same continent
*/
public function getNeighboringCountries(string $code=''): array {
$code = strtoupper($code);
$country = $this->getCountryByCode($code);
if (!$country) {
return [];
}
return array_filter($this->countries, function ($c) use ($country, $code) {
return $c['continent'] === $country['continent'] && $c['alpha_3'] !== $country['alpha_3'];
});
}
/**
* Get timezone information for a country
* @param string $code Country code
* @return array|null Timezone information or null if not found
*/
public function getCountryTimezones(string $code=''): ?array {
if (empty($code)) {
return null;
}
$code = strtoupper($code);
if (!isset($this->countries[$code])) return null;
return [
'timezones' => DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $code),
'current_time' => array_map(function($timezone) {
$tz = new DateTimeZone($timezone);
$time = new DateTime('now', $tz);
return [
'timezone' => $timezone,
'time' => $time->format('Y-m-d H:i:s'),
'offset' => $tz->getOffset($time)
];
}, DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $code))
];
}
/**
* Get currency details by code.
* @param string $currencyCode Currency code.
* @return array|null Currency details or null if not found.
*/
public function getCurrencyDetailsByCode(string $currencyCode=''): ?array {
if (empty($currencyCode)) {
return null;
}
$currencyCode = strtoupper($currencyCode);
foreach ($this->countries as $country) {
if ($country['currency_code'] === $currencyCode) {
return [
'code' => $currencyCode,
'name' => $country['currency_name'],
'symbol' => $country['currency_symbol'],
'countries' => $this->getCountriesByCurrency($currencyCode)
];
}
}
return null;
}
/**
* Generates an HTML img tag for a country flag based on the country code
*
* @param string $code The country code (default: 'US'). Must be a valid ISO 3166-1 alpha-2 code.
* @param string $type The image format ('png', 'webp', 'svg', or 'jpg'). Defaults to 'png'.
* @param string $size The size of the flag. For 'png' and 'webp', use dimensions like '256' (default).
* For 'jpg', use width-based sizes like '320'. SVG ignores the size.
* @return string The generated HTML `<img>` tag with the appropriate flag image.
*/
public function getCountryFlag($code = 'US', $type = 'png', $size = '256') {
// Define supported image types
$image_types = [
'png' => 'png',
'webp' => 'webp',
'svg' => 'svg',
'jpg' => 'jpg',
];
// Define sizes for JPG images
$image_size_jpg = [
'20' => 'w20',
'40' => 'w40',
'80' => 'w80',
'160' => 'w160',
'320' => 'w320',
'640' => 'w640',
'1280' => 'w1280',
'2560' => 'w2560',
];
// Define sizes for PNG and WebP images
$image_size = [
'16' => '16x12',
'20' => '20x15',
'24' => '24x18',
'28' => '28x21',
'32' => '32x24',
'36' => '36x27',
'40' => '40x30',
'48' => '48x36',
'56' => '56x42',
'60' => '60x45',
'64' => '64x48',
'72' => '72x54',
'80' => '80x60',
'84' => '84x63',
'96' => '96x72',
'108' => '108x81',
'112' => '112x84',
'120' => '120x90',
'128' => '128x96',
'144' => '144x108',
'160' => '160x120',
'192' => '192x144',
'224' => '224x168',
'256' => '256x192',
];
// Ensure code is in lowercase
$code = strtolower(trim($code));
if (empty($code)) {
return '';
}
$alt = '';
$get_country = $this->getCountryByCode($code);
if ($get_country) {
$alt = htmlspecialchars($get_country['name'], ENT_QUOTES, 'UTF-8');
}
$domain = 'https://flagcdn.com/';
$type = $image_types[$type] ?? 'png';
$image_tag = '';
if ($type === 'png' || $type === 'webp') {
$size = $image_size[$size] ?? '256x192';
[$width, $height] = explode('x', $size);
$image_tag = "<img src=\"{$domain}{$size}/{$code}.{$type}\" width=\"{$width}\" height=\"{$height}\" alt=\"{$alt}\">";
} elseif ($type === 'jpg') {
$size = $image_size_jpg[$size] ?? 'w320';
$width = (int)filter_var($size, FILTER_SANITIZE_NUMBER_INT);
$image_tag = "<img src=\"{$domain}{$size}/{$code}.jpg\" width=\"{$width}\" alt=\"{$alt}\">";
} else { // SVG fallback
$image_tag = "<img src=\"{$domain}{$code}.svg\" width=\"{$size}\" alt=\"{$alt}\">";
}
return $image_tag;
}
/**
* Generates an HTML `<img>` tag for a country's coat of arms based on the provided parameters.
*
* @param string $code The country code (default: 'US'). Must be a valid ISO 3166-1 alpha-2 code.
* @param string $type The image format ('png' or 'svg'). Defaults to 'png'.
* @param array $attributes Additional HTML attributes to include in the `<img>` tag (e.g., ['class' => 'img-fluid']).
* @return string The generated HTML `<img>` tag with the appropriate coat of arms image.
*/
public function getCountryCoatOfArms($code = 'US', $type = 'png', $attributes = []) {
// Define supported image types
$image_types = [
'png' => 'png',
'svg' => 'svg',
];
// Ensure the country code is lowercase and trimmed
$code = strtolower(trim($code));
if (empty($code)) {
// Return an empty string if the code is not provided
return '';
}
// Fetch country information to set the alt text
$alt = '';
$get_country = $this->getCountryByCode($code);
if ($get_country) {
// Use the country's name for the alt attribute, sanitized for HTML
$alt = htmlspecialchars($get_country['name'], ENT_QUOTES, 'UTF-8');
}
// Process additional HTML attributes
$attributesStr = '';
if (is_array($attributes)) {
foreach ($attributes as $key => $value) {
// Sanitize attribute keys and values to prevent XSS
$attributesStr .= " {$key}=\"" . htmlspecialchars($value, ENT_QUOTES) . "\"";
}
}
// Define the base domain for the coat of arms images
$domain = 'https://mainfacts.com/media/images/coats_of_arms/';
// Validate and default the image type
$type = $image_types[$type] ?? 'png';
// Build and return the complete <img> tag
return "<img src=\"{$domain}{$code}.{$type}\" alt=\"{$alt}\"$attributesStr>";
}
}
The CountryManager
class provides extensive functionality to manage and retrieve country-related data. Use the examples above as a guide to integrate it into your projects seamlessly.
Download all zip file
Download ZipHow to Use the CountryManager Class
The CountryManager class is a powerful tool for managing country-related data. This section explains how to use its various functions effectively. Follow the examples below to integrate the class into your projects.
Instantiating The Class
To start using the CountryManager
class, initialize it with the $country_list
array:
Retrieving Country Details
Use the following methods to fetch country-specific data
Get Country by Code:
$country = $countryManager->getCountryByCode('US');
print_r($country);
// output
/*
Array (
[name] => United States
[phone] => 1
[alpha_3] => USA
[continent] => North America
[continent_code] => NA
[capital] => Washington
[currency_code] => USD
[currency_symbol] => $
[currency_name] => United States dollar
)
*/
Output: Details about the United States.
Get Country Name By Code:
Get Phone Code By Country Code:
$country_code = 'IN';
$phoneCode = $countryManager->getPhoneCode($country_code);
echo $phoneCode; // Output: 91
Get Country By Capital Name:
$contry = $countryManager->getCountryByCapital('New Delhi');
print_r($contry);
// output array
/*
Array(
[name] => India
[phone] => 91
[alpha_3] => IND
[continent] => Asia
[continent_code] => AS
[capital] => New Delhi
[currency_code] => INR
[currency_symbol] => ₹
[currency_name] => Indian rupee
)
*/
Get Capital By Country Code:
Get All Continents:
Validating and Counting
Check if a Country Code is Valid:
$country_code = 'BR'; // Brazil
$isValid = $countryManager->isValidCountryCode($country_code);
if ($isValid) {
echo "Valid country code";
} else {
echo "Invalid country code. Please provide a valid ISO 3166-1 alpha-2 code";
}
Count Countries by Continent:
$counts = $countryManager->countCountriesByContinent();
print_r($counts);
// output array
/*
Array(
[Asia] => 55
[Europe] => 52
[Africa] => 58
[Australia (Oceania)] => 25
[North America] => 43
[Antarctica] => 5
[South America] => 14
)
*/
Output: Number of countries in each continent.
Working with Currencies
Get Countries by Currency Code:
$countriesUsingUSD = $countryManager->getCountriesByCurrency('USD');
print_r($countriesUsingUSD);
Get Currency Details:
$currency_code = 'EUR'; // Euro
$currencyDetails = $countryManager->getCurrencyDetailsByCode($currency_code);
print_r($currencyDetails);
// output array
/*
Array
(
[code] => EUR
[name] => Euro
[symbol] => €
[countries] => Array()
)
*/
Output: Details about the Euro.
Filtering and Searching
Get Countries by Continent:
$countriesInAsia = $countryManager->getCountriesByContinent('Asia');
print_r($countriesInAsia);
// output
/*
Array (
[AF] => Array (
[name] => Afghanistan
...
)
[AM] => Array (
[name] => Armenia
...
)
...
)
*/
Output: List of countries in Asia.
Search Countries by Name:
Output: Countries with "land" in their name.
Advanced Operations
Get Neighboring Countries:
$country_code = 'CA'; // Canada
$neighbors = $countryManager->getNeighboringCountries($country_code);
print_r($neighbors);
Output: Countries in the same continent as Canada.
Get Timezones
Get Timezones by country ISO 2 code
$country_code = 'IN'; // India
$timezones = $countryManager->getCountryTimezones($country_code);
print_r($timezones);
// output array
/*
Array (
[timezones] => Array (
[0] => Asia/Kolkata
)
[current_time] => Array (
[0] => Array (
[timezone] => Asia/Kolkata
[time] => 2025-01-19 01:42:55
[offset] => 19800
)
)
)
*/
Output: Timezone information for India.
Get Country Flag Image
Generating an HTML <img> tag for a country's flag using its ISO 3166-1 alpha-2 country code.
PNG, JPG, WEBP, SVG country flag Image
$country_code = 'IN';
$type = 'png'; // png, jpg, svg, webp
$size = 256;
/**
size support
PNG and WEBP [16,20,24,28,32,36,40,48,56,60,64,72,80,84,96,108,112,120,128,144,160,192,224,256]
JPG [20,40,80,160,320,640,1280,2560]
SVG any size
**/
echo getCountryFlag($country_code, $type, $size);
// output
// <img src="https://flagcdn.com/256x192/in.png" width="256" height="192" alt="India">
Get Country Coat Of Arms Image
Generating Dropdowns
The generateDropdown
function creates customizable dropdown menus for countries, phone codes, or currencies.
Country Dropdown
$selected_country_code = 'US';
$attributes = [
'class' => 'form-control',
'name' => 'country',
'id' => 'country'
];
echo $countryManager->generateDropdown('country', $attributes, $selected_country_code);
// OR
// echo '<select id="country">'.$countryManager->getCountryDropdown('US').'</select>';
// without selected
// echo '<select id="country">'.$countryManager->getCountryDropdown().'</select>';
// output
/*
<select class="form-control" name="country-select" id="country-select">
<option value="">Select a country</option>
<option value="AF">Afghanistan</option>
<option value="AX">Åland Islands</option>
<!-- ... -->
<option value="US" selected>United States</option>
</select>
*/
Output: A country dropdown with the United States pre-selected.
Phone Code Dropdown
$selected_country_code = 'IN';
$attributes = [
'class' => 'form-control',
'name' => 'phone',
'id' => 'phone'
];
echo $countryManager->generateDropdown('phone', $attributes, $selected_country_code);
// OR
// echo '<select id="phone">'.$countryManager->getPhoneCodeDropdown('IN').'</select>';
// without selected
// echo '<select id="phone">'.$countryManager->getPhoneCodeDropdown().'</select>';
// output
/*
<select class="form-control" name="phone" id="phone">
<option value="">Phone</option>
<option value="93">Afghanistan (+93)</option>
<option value="358">Åland Islands (+358)</option>
<!-- ... -->
<option value="91" selected>India (+91)</option>]
</select>
*/
Output: A dropdown of phone codes.
Currency Dropdown
$selected_currency_code = 'USD';
$attributes = [
'class' => 'form-control',
'name' => 'currency',
'id' => 'currency'
];
echo $countryManager->generateDropdown('currency', $attributes, $selected_currency_code);
// OR
// echo '<select id="currency">'.$countryManager->getCurrenciesDropdown('USD').'</select>';
// without selected
// echo '<select id="currency">'.$countryManager->getCurrenciesDropdown().'</select>';
// output
/*
<select class="form-control" name="currency" id="currency">
<option value="">Currency</option>
<option value="AFN">Afghan afghani</option>
<!-- ... -->
<option value="AED">United Arab Emirates dirham</option>
<option value="USD" selected>United States dollar</option>
</select>
*/
Output: A dropdown of currencies.
Continents Dropdown
$selected_continent_code = 'USD';
$attributes = [
'class' => 'form-control',
'name' => 'continent',
'id' => 'continent'
];
echo $countryManager->generateDropdown('continent', $attributes, $selected_continent_code);
// OR
// echo '<select id="continent">'.$countryManager->getCurrenciesDropdown('AS').'</select>';
// without selected
// echo '<select id="continent">'.$countryManager->getCurrenciesDropdown().'</select>';
// output
/*
<select class="form-control" name="continent" id="continent">
<option value="">Continent</option>
<option value="AF">Africa</option>
<option value="AN">Antarctica</option>
<option value="AS" >Asia</option>
<option value="EU">Europe</option>
<!-- ... -->
</select>
*/
Output: A dropdown of continents.
Related: