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 create random numbers in JS?

How to prevent Eloquent from adding created_at or updated_at timestamps?

How do Invokable Controllers work in Laravel?

How to hide the server signature (hide Apache info) from HTTP headers with .htaccess

How to select what columns to return when calling ::all()

How to block IPv6 IP addresses in .htaccess

Set PHP config Variables (like ini_set) with .htaccess

How to hide certain file types from directory listings

How to force non www in htaccess

How to replace values in a string, in JS