Building query strings in PHP
Posted on 15. Jul, 2009 by Nikhil Sheth in PHP, Tips
Passing query parameters in the url is something which most of the programmers encounters everyday. Typical way of doing is keep on appending parameters in a variable.
ex:
$fname=”Nikhil”;
$lname=”Sheth”;
$city=”Mumbai”;
$myUrl=”http://www.nikhilsheth.net/example.php?fname={$fname}&lname={$lname}&city={$city}”;
This is fine if you have to add just 1 or 2 query paramters in the url. But it would be difficult if you need to pass large number of query parameters.
In such scenarios, php function http_build_query() turns out to be very handy. This function is available from PHP 5.
It takes an array of variables and builds a nice URL encoded string which you can append to a url.
$fields=array(“fname”=>”Nikhil”,”lname”=>”Sheth”,”city”=>”Mumbai”);
$myUrl=”http://www.nikhilsheth.net/example.php?”.http_build_query($fields,”,”&”);
In the above example the array contained the variable names and their values. You can also pass an array containing only values and let the function fill the variable name using the array index and a variable you supply (as a second parameter).
Ex:
$fields=array(“Nikhil”,”Sheth”,”Mumbai”);
$myUrl=”http://www.nikhilsheth.net/example.php?”.http_build_query($fields,’param’,”&”);
The generated url will look like:
http://www.nikhilsheth.net/example.php?param0=Nikhil¶m1=Sheth¶m2=Mumbai;
Third parameter is optional. By default it would take & as separator. But you can pass any other parameter if required.
Related posts:

Leave a reply