Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

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 2 days ago by avibootz
...