It’s common knowledge you can read variable from a URL querystring by using $_GET array in PHP, but that’s only possible if the URL is “executed” in the browser.

For those who might not know, querystrings are those variable-value pairs that appears behind ‘?’ of a URL. For example,

http://www.mysite.com/index.php?variable1=1&variable2=1

gives the querystring “variable1=1&variable2=1”.

What happens if you end up reading a URL from, say, a text file and you want to parse the querystring? In this case, the $_GET won’t work. So instead, PHP provides a function called parse_str(), which will convert the querystring into actual PHP variables within the scope of the code.

This is what happens when you use the function.

As you can see, parse_str has converted the variable-value pairs, like “first=1” into a PHP variable $first which has a value of 1, and so on.

In addition, parse_str can also take in an array as an optional second parameter like this:

The difference here is that the querystring variables are stored as keys within the array $myArray. Once it’s in an array, you can more easily manipulate and read the variables by cycling through the array.

On the flip side, you can do the opposite of parse_str by using the function call http_build_query().