How to Get Key/Value Pair from URL Query String in PHP?

A look at different ways to retrieve the query string and parameter values therein

In this article we look at different ways in PHP to retrieve the query string and its parameter values from a URL. We'll be using the following string for all the examples in this article:

http://www.designcise.com/?key1=value1&key2=value2

Retrieving the Query String

Query String of Current URL:

Using $_SERVER['QUERY_STRING'] in PHP we can get the full query string from the current URL. For example:

echo $_SERVER['QUERY_STRING']; 

// Output: key1=value1&key2=value2

Query String From a String:

To retrieve the query string from a string we can use the parse_url function. For example:

echo parse_url('http://www.designcise.com/?key1=value1&key2=value2', PHP_URL_QUERY);

// Output: key1=value1&key2=value2

Query String Parameters as an Array

Using the $_GET Superglobal:

Using $_GET array in PHP we can directly access any key/value pair in the current URL. For example:

echo $_GET['key1']; // Output: value1

Parsing a Query String:

When we have all the key/value pairs in a single string, we can use the parse_str function to convert the key/value pairs to an array:

// method #1
parse_str($_SERVER['QUERY_STRING'], $output);

// method #2
parse_str(parse_url('http://www.designcise.com/?key1=value1&key2=value2', PHP_URL_QUERY), $output);
echo print_r($output, true);

// Output:
Array (
    ['key1'] => "value1"
    ['key2'] => "value2"
)

Handling Duplicate Keys in a Query String:

Using either of the two methods explained above, the output of duplicate keys in a query string would be a child array for that key with numerically indexed values. For demonstration purposes, consider the output of the following url:

http://www.designcise.com/?key[]=value1&key[]=value2

// Output:
Array (
    ['key'] => Array (
        [0] => test1
        [1] => test2
    )
)

Things to Remember:

When using the methods explained above, remember the following are true:

  • Using $_GET would be the fastest way to access a key/value pair in the current url. Wherever possible, this should be the preferred choice.
  • Both parse_str and $_GET automatically urldecode values, which means any %## encoding is decoded in the given string. Plus symbols (i.e. +) are decoded to a space character. If this is not the behavior you're looking for, then you may use $_SERVER['QUERY_STRING'] to retrieve the entire query string in its original form or call urlencode on individual values.
  • Duplicate key names followed by square brackets (for example, ?key[]=value1&key[]=value2) create a child array for that key with numerically indexed values.

Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.