How to Extract Query String (from a URL) Into an Associative Array in PHP

October 26, 2018

If you have a query string (such as ?a=foo&b=bar) and want to convert that into a PHP array, this is how to do it.

Let's take a full example, where we begin with a URL, get the query string part of it, then convert that into an array.

        $url = "";
        $parsed_url = parse_url($url);
        // $parsed_url is an array of the parts of the URL, such as host, query_string, path, etc
        $query_string = $parsed_url["query"];
        // $query_string is now foo=bar&foo2=bar2
        // now let's convert that into an array:
        // don't forget the 2nd param - it is the variable where the array will be
        return $array_of_query_string;
array(2) {

["foo"]=> string(3) "bar"

["foo2"]=> string(4) "bar2"