How to get the country name from the 2-letter country code (alpha-2) in PHP

1 Answer

0 votes
/* ------------------------------------------------------------
   getCountryName
   Receives a 2‑letter ISO country code and returns the
   corresponding country name.

   Uses an associative array for O(1) lookups.
   Input is normalized to uppercase to ensure consistent matching.
   Returns null if the code is not found.
------------------------------------------------------------ */
function getCountryName(string $alpha2): ?string
{
    // Static lookup table; extend as needed
    static $countryMap = [
        'CA' => 'Canada',
        'CN' => 'China',
        'DE' => 'Germany',
        'FR' => 'France',
        'GB' => 'United Kingdom',
        'KR' => 'South Korea',
        'IN' => 'India',
        'JP' => 'Japan',
        'US' => 'United States'
    ];

    // Normalize input
    $code = strtoupper(trim($alpha2));

    // Lookup
    return $countryMap[$code] ?? null;
}

/* ------------------------------------------------------------
   Demonstration
------------------------------------------------------------ */
$codes = ['US', 'GB', 'FR', 'JP', 'ZZ']; // ZZ is intentionally invalid

foreach ($codes as $code) {
    $name = getCountryName($code);

    if ($name !== null) {
        echo "$code → $name\n";
    } else {
        echo "$code → (invalid code)\n";
    }
}



/*
run:

US → United States
GB → United Kingdom
FR → France
JP → Japan
ZZ → (invalid code)

*/

 



answered Sep 19 by avibootz
...