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

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:


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:


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:


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:


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).

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.