Search code examples
phparraysassociative-arraytext-parsing

Converting a comma separated string of attribute declarations into an associative array


I have a string - something like

$string = 'key1=value1, key2=value2, key3=value3';

How can I get an array from the given string like the following?

$array = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
);

Solution

  • If the values (text on the right side of the = symbols) do not have any characters with special meaning in a URL's querystring AND a value will never be null, then you won't have any unexpected results using parse_str() after converting the input to valid querystring format.

    $string = 'key1=value1, key2=value2, key3=value3';
    parse_str(
        str_replace(", ", "&", $string),
        $array
    );
    var_export($array);
    

    Demo