phparraysinitext-parsingstring-parsing

How to parse an ini-formatted string into an associative array?


I'm trying to break up this string,

AFRIKAANS = af
ALBANIAN = sq
AMHARIC = am
ARABIC = ar
ARMENIAN = hy
AZERBAIJANI = az
BASQUE = eu
BELARUSIAN = be
BENGALI = bn
BIHARI = bh
BULGARIAN = bg
BURMESE = my
CATALAN = ca
CHEROKEE = chr
CHINESE = zh

Into an array like this

$lang_codes['chinese'] = "zh";

So the name of the language is the key, and the value is the language code. This is really simple, but I just can't get my head around it. I've taken a brake from programming, too long, obviously...

I've tried exploding at \n then using a foreach, exploding again at = but I can't seem to piece it together the way I want.


Solution

  • I've tried exploding at \n then using a foreach, exploding again at " = "

    I think this is exactly the right approach.

    $lines = explode("\n", $langs);
    $lang_codes = array();
    
    foreach ($lines as $line) {
        list ($lang, $code) = explode(" = ", $line, 2);
        $lang_codes[$lang] = $code;
    }
    

    If you want the language to be in lowercase, as in your example ($lang_codes['chinese']), you'll need to call strtolower:

    $lang_codes[strtolower($lang)] = $code;
    

    See the PHP manual for more on these functions: