Parsing a URL querystring into variables in PHP

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.

<?php
$myQryStr = "first=1&second=Z&third[]=5000&third[]=6000";
parse_str($myQryStr);
echo $first; //will output 1
echo $second; //will output Z
echo $third[0]; //will output 5000
echo $third[1]; //will output 6000
?>

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:

<?php
$myQryStr = "first=1&second=Z&third[]=5000&third[]=6000";
parse_str($myQryStr, $myArray);
echo $myArray['first']; //will output 1
echo $myArray['second']; //will output Z
echo $myArray['third'][0]; //will output 5000
echo $myArray['third'][1]; //will output 6000
?>

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

Leave a comment