Search code examples
phparraysexplodetext-parsing

Convert a string with 2 delimiters into a flat associative array


Here is a string..

$string = "foo1 : bar1, foo2: bar2, foo3: bar3"; 

Exploding using , delimeter

$exploded = (",", $string);

Now the $exploded array contains:

foo1 : bar1
foo2 : bar2
foo3 : bar3

Now I need to put foo1 in an array['key'] and bar1 in array['value']

How to achieve this?


Solution

  • You'll need to create another loop to go through an array of "foo:bar" strings and explode them:

    $exploded = explode(",", $input);  
    $output = array();       //Array to put the results in
    foreach($exploded as $item) {  //Go through "fooX : barX" pairs
      $item = explode(" : ", $item); //create ["fooX", "barX"]
      $output[$item[0]] = $item[1];  //$output["fooX"] = "barX";
    }
    print_R($output);
    

    Note that if the same key appears more than once in the input string - they will overwrite each other and only the last value will exist in the result.