How to Extract Query String (from a URL) Into an Associative Array in PHP

PHP: How to Extract Query String (from a URL) Into an Associative Array in PHP

If you have a query string (such as ?a=foo&b=bar) and want to convert that into a PHP array, this is how to do it.

Let's take a full example, where we begin with a URL, get the query string part of it, then convert that into an array.

  1.         $url = "https://example.com/?foo=bar&foo2=bar2";
  2.         $parsed_url = parse_url($url);
  3.         // $parsed_url is an array of the parts of the URL, such as host, query_string, path, etc
  4.         $query_string = $parsed_url["query"];
  5.         // $query_string is now foo=bar&foo2=bar2
  6.  
  7.         // now let's convert that into an array:
  8.         // don't forget the 2nd param - it is the variable where the array will be
  9.          parse_str($query_string,$array_of_query_string);
  10.  
  11.  
  12.         return $array_of_query_string;

array(2) {
      ["foo"]=> string(3) "bar"
      ["foo2"]=> string(4) "bar2"
      }
webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to Extract Query String (from a URL) Into an Associative Array in PHP

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the PHP language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to show (or log) all SQL queries executed by Laravel

How do you run a PHP script from the command line?

How to find the 2nd most common item in an array?

How to block IPv6 IP addresses in .htaccess

What are the SPL data structures

How to set up an alias to map one directory to another destination

How to generate an array for a dropdown (with ['key' => 'value']) suitable for a dropdown, from a Laravel collection of Eloquent objects?

What are Apache MPMs?

Point all requests to one PHP file

How to add comments in PHP