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

Quick and easy ways to get URL query string key/value pairs

In this post, you're going to learn how to get the key/value pairs from the current page's URL query string. Please note that this is different from extracting key/value params from a string URL.

Access Individual URL Query String Params

You may simply use the $_GET superglobal to access individual params from the query string, for example, like so:

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

echo $_GET['key1']; // output: 'value1'
echo $_GET['key2']; // output: 'value2'

Please be aware of the fact that $_GET automatically passes the params through urldecode(). Therefore, if you explicitly use urldecode() on $_GET elements, you may end up with problems.

Also, take note of the fact that duplicate key names followed by square brackets (for example, ?key[]=value1&key[]=value2) create a child array for that key with numerically indexed values. For example:

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

echo $_GET['key'][0]; // output: 'value1'
echo $_GET['key'][1]; // output: 'value2'

Similarly, if the squared brackets had some text between them, the child array belonging to the key would be an associative array. For example:

// https://designcise.com/?key[foo]=value1&key[bar]=value2

echo $_GET['key']['foo']; // output: 'value1'
echo $_GET['key']['bar']; // output: 'value2'

Extract URL Query Params as String

You can also extract the query string part from the current page's URL using the $_SERVER array like so:

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

echo $_SERVER['QUERY_STRING']; // output: 'key1=value1&key2=value2'

Which you can then convert to an array if you need (i.e. if for some reason you do not wish to use $_GET).


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