Thursday, June 24, 2010

Parse a query string into an array of key/value pairs using PHP

If you happen to need to parse a query string that is not a part of the current http request, here is a function that will do that. It's pretty basic, you may wish to add url encode checking, but the pattern works great and returns an associative array of the key, value pairs.

function get_query_vars($query_str){
$pairs = array();
$parts = explode('&',$query_str);
for($i=0,$n=count($parts);$i<$n;$i++)
{
if(stristr($parts[$i],"=")){
$pair=explode('=',$parts[$i]);
$pairs[$pair[0]]=$pair[1];
}
}
return $pairs;
}

No comments:

Post a Comment