Converting a querystring into an associative array

In PHP, I need a function to convert a querystring from an URL, say: http://example.com?key1=value1&key2=value2 into a PHP associative array : array ['key1' => 'value1', 'key2' => 'value2'].

I've come up to this piece of code. It works, but I find it a bit lengthy. (And PHP has built-in functions for everything: I'm surprised I haven't found anything out-of-the-box, something like the reverse of http_build_query.)

Can you suggest a better way to do this?

function getUrlParams($url) {
  $querystring = parse_url($url, PHP_URL_QUERY);
  $a = explode("&", $querystring);
  if (!(count($a) == 1 && $a[0] == "")) {
    foreach ($a as $key => $value) {
      $b = explode("=", $value);
      $a[$b[0]] = $b[1];
      unset ($a[$key]);
    }
    return $a;
  } else {
    return false;
  }
}

Answers


You can get just the atributes from a URL using parse_url()

Once you have that you can use parse_str() to convert them to variables, it works with multidimensional arrays too!

$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

Need Your Help

JWSC for weblogic 12c with Maven

web-services maven weblogic weblogic12c

We are in the process of upgrading from Weblogic 10g to 12c. A portion of our code base is webservices so we were using weblogic-maven-plugin:

How to instruct sbt 0.11.x which source files contain tests

scala sbt specs

I'm new to Scala, SBT and Specs. I have created a simple specification using specs and like to run it via SBT with the "test" task. When I execute that task, I get the following error:

Customise UITableView

iphone ios uitableview xcode4

How can I use more than one UITableView in one ViewController? Is it possible to ause more than one TableView in a page?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.