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 find the index of a value in an array in JS?

What are route patterns in Laravel?

What are some ways you can log debug messages and data in JS?

How could you include a custom function for every single time PHP runs?

How to autoload helper files with composer?

What are the predefined variables in PHP?

What is the difference between reference and primitive data types types in Javascript?

Force trailing slash (redirect if no trailing slash exists) in .htaccess

How to set custom HTTP headers in Apache (by editing .htaccess)

How to get a route to directly show a view?