Monday 16 July 2018

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

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:

  1. $myArray = array(  
  2.     "car"=>"ford",  
  3.     "animal"=>"elephant",  
  4.     "language"=>"php"  
  5. );  
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():

  1. echo http_build_query($myArray);  
  2.   
  3. // Outputs: car=ford&animal=elephant&language=php  
How easy was that! The function also works with multi-dimensional arrays as shown below:

  1. $myArray = array(  
  2.     "car"=>array("ford""vauxhall""dodge"),  
  3.     "animal"=>"elephant",  
  4.     "language"=>"php"  
  5. );  
  6.   
  7. echo http_build_query($myArray);  
  8.   
  9. // 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:
  1. 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:

  1. $queryString = "car=ford&animal=elephant&language=php";  
  2.   
  3. parse_str($queryString$output);  
  4.   
  5. 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:
  1. Array  
  2. (  
  3.     [car] => ford  
  4.     [animal] => elephant  
  5.     [language] => php  
  6. )  
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.

1 comment:

  1. thanks for sharing this information i search this information for quite time and finally got this in your blog keep updating like this post
    PHP Training Institute in Chennai
    Dot Net Training in Chennai
    Java Training Institute in Chennai
    Software Testing Course in Chennai

    ReplyDelete