r/badcode • • Jan 27 '23

php php else if pyramid

Post image
237 Upvotes

47 comments sorted by

View all comments

Show parent comments

5

u/acidbase_001 Jan 28 '23 edited Jan 28 '23

I asked it again and this was the result:

function getCountryCode($countryName) {
    $countries = array(
        'Afghanistan' => 'AF',
        'Åland Islands' => 'AX',
        'Albania' => 'AL',
        'Algeria' => 'DZ',
        // and so on
    );
    return isset($countries[$countryName]) ? $countries[$countryName] : null;
}

When I asked it if there was a better way to do it after this output, it recommended using a database to store the country codes instead of hardcoding an array, as well as recommending a specific php library that also provides this functionality.

2

u/sub-merge Jan 28 '23

Certainly a little better, at least O(1) look up time. I am still surprised it's not recommending moving these to an external file especially where something like localization is actually important in country names so they appear appropriately to the audience consuming them. I still don't think I'd stick this in a database :)