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

Remove trailing slash (redirect to remove trailing slash) in .htaccess

What are Template literals (Template strings) in JS?

How to disable file hotlinking in Apache with .htaccess

How to manually write your own pagination in PHP

What are PHP's PSRs?

How to Enable Directory Listings in Apache with .htaccess

How to redirect your website to a new domain/location in .htaccess

What is camel case?

What is the difference between empty(), isset(), != null, is_null() in PHP

How to add the CSRF (Cross-site request forgery) token in Laravel?