chip chip - 5 months ago 8
PHP Question

Line and colon separated list to array PHP

I'm trying to work out a simple way to take a list, like this

foo: Alpha
bar: Bravo
fooBar: Charlie


And turn this into an associative array so that values would be

$array['foo'] //would contain Alpha
$array['bar'] //would contain Bravo


etc.

What is the cleanest way to achieve this ?

Answer

Something like this?:

$string = "foo: Alpha
bar: Bravo
fooBar: Charlie";

$array = array();
$lines = explode("\n", $string);

foreach ($lines as $line) {
    list($key, $value) = explode(": ", $line);
    $array[$key] = $value;
}

var_dump($array);


Result:

array(3) {
  ["foo"]=>
  string(6) "Alpha
"
  ["bar"]=>
  string(6) "Bravo
"
  ["fooBar"]=>
  string(7) "Charlie"
}
Comments