Converting a PHP Array to a Query String… And Back Again

May 18th, 2011 - Posted by Steve Marks to PHP, Web Development.

This is a scenario I have found myself in many times before; needing to convert a PHP array to a query string for use in a URL or POST request, and vice versa. Today I will discuss both methods and how they can be achieved with the aid of two very useful PHP functions; http_build_query() and parse_str().

Generating a URL query string from a PHP array

For the first part of this post let us take a look at the following PHP array:

$myArray = array(

Simple enough right? Just three elements in a single-dimension array. Now lets take a look at how we can convert this to a query string using our first function http_build_query():

echo http_build_query($myArray);

// Outputs: car=ford&animal=elephant&language=php

How easy was that! The function also works with multi-dimensional arrays as shown below:

$myArray = array(
	"car"=>array("ford", "vauxhall", "dodge"),

echo http_build_query($myArray);

// Outputs: car[0]=ford&car[1]=vauxhall&car[2]=dodge&animal=elephant&language=php

We can get as simple or as complex as we like but I’ll let you play around with the function to get it working for you. Pretty useful stuff I think you’ll agree?!? Now lets look at the opposite effect of turning our query strings back into an array.

Creating a PHP array based on a query string

For this i want to refer back to the query string we generated in our first example. If you’ve forgotten it looks a little like this:


It’s time to welcome our second function of today, parse_str(). Let’s put it in into action:

$queryString = "car=ford&animal=elephant&language=php";

parse_str($queryString, $output);


If done right the output will be a PHP array called $output (note the second parameter we used) containing three elements. We can see this below:

    [car] => ford
    [animal] => elephant
    [language] => php

So there we have it. In just a couple of lines we’ve gone from an array, to a query string, and back to an array again.

Tags: , ,
This entry was posted on Wednesday, May 18th, 2011 at 9:37 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (6)
  1. Anonymous says:

    sweet ;-)

  2. The first part of this post explains how to do exactly what you’re after. Tip: Use the http_build_query() function.

  3. I use the function parseurl to get array from url and then unset some field. I want to get url from that array :-? please help me to get it. Thank you very much in advance!

  4. Ankush Jetly says:

    Superb !! really u saved ma day !!!

  5. @Gav – Haha, that’s good to know… Glad I can be of some help!

  6. Gav says:

    Whenever I google stuff like this your site always seems to come up first! Thanks man – simple yet very effective snippet ;-)