Converting a PHP Array to a Query String… And Back Again
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(
- "car"=>"ford",
- "animal"=>"elephant",
- "language"=>"php"
- );
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"),
- "animal"=>"elephant",
- "language"=>"php"
- );
- 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:
- car=ford&animal=elephant&language=php
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);
- print_r($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:
- Array
- (
- [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.
thanks for sharing this information i search this information for quite time and finally got this in your blog keep updating like this post
ReplyDeletePHP Training Institute in Chennai
Dot Net Training in Chennai
Java Training Institute in Chennai
Software Testing Course in Chennai