chip chip - 1 year ago 64
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


What is the cleanest way to achieve this ?

Answer Source

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;



array(3) {
  string(6) "Alpha
  string(6) "Bravo
  string(7) "Charlie"