Search code examples
phparraysquery-string

Parse query string into an associative array


Is there an already existing function in PHP for creating an associative array from a delimited string? If not, what would be the most effective means of doing so? I am looking at PayPal's new NVP API, where requests and responses have the following format:

 method=blah&name=joe&id=joeuser&age=33&stuff=junk

I can use explode() to get each pair into an array value, but it would be even better if I could do some sort of function like dictionary_explode and indicate the key-value delimiter and get back an associate array like:

Array {
 [method] => blah
 [name] => joe
 [id] => joeuser
 [age] => 33
 [stuff] => junk

}

My CS friends tell me that this idea exists in other languages like Python, so I'm wondering if I just haven't found such a thing for PHP. Right now I'm looking at doing an array_walk, but I'd prefer something more pre-built.


Solution

  • PHP has an inbuilt function for it: parse_str()

    <?php
    $str = "first=value&arr[]=foo+bar&arr[]=baz";
    parse_str($str);
    echo $first;  // value
    echo $arr[0]; // foo bar
    echo $arr[1]; // baz
    
    parse_str($str, $output);
    echo $output['first'];  // value
    echo $output['arr'][0]; // foo bar
    echo $output['arr'][1]; // baz
    
    ?>
    

    Note: My recommendation is to not use the first form (parse_str($str)) for the same reason register_globals is bad. The second form (parse_str($str, $arr)) is always preferred.