in Php Basics

Parse URL Querystring Into Array In PHP

PHP Using query strings in PHP is a good way of transferring data from one file to another. This is done by using the $_GET variable. This variable is a global variable that is used to get the content of the query string and allow you to get at this data as an array. Getting at data in a query string can be used in other places in your application for example using Ajax requests you may need to get the contents of a query string. Here is a PHP snippet that will take a query string as a parameter and return an array of the query string data.

        * Parse out url query string into an associative array
        * $qry can be any valid url or just the query string portion.
        * Will return false if no valid querystring found
        * @param $qry String
        * @return Array
        function queryToArray($qry)
                $result = array();
                //string must contain at least one = and cannot be in first position
                if(strpos($qry,'=')) {
                 if(strpos($qry,'?')!==false) {
                   $q = parse_url($qry);
                   $qry = $q['query'];
                }else {
                        return false;
                foreach (explode('&', $qry) as $couple) {
                        list ($key, $val) = explode('=', $couple);
                        $result[$key] = $val;
                return empty($result) ? false : $result;

PHP Function parese_str

PHP has a built in function to perform this task and convert a query string into an array so that you can loop through the parameters and perform the tasks you need to. This PHP function is called parse_str(), it takes two parameters but the second is optional. The first parameter will be a string which will be the query string and the return of the function will create variables from the query string.

$str = "first=value&arr[]=foo+bar&arr[]=baz";
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

If you give this a second parameter then the return of this will add query string into an array or key value pairs.

$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

Build A Query String From Array

Along with turning a query string into an array there is also a PHP function that will turn an array into a query string. This function is called http_build_query() which takes an array and will return a query string of the key value pair of the array.

$query = array('val' => 1, 'test' => 2, 'key' => 'value');
$string = http_build_query( $query );

echo $string; // this will return val=1&test=2&key=value