Over a million developers have joined DZone.

PHP: Fetch $_GET as String with http_build_query()

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

PHP is really full of functions for everything! Most of the time when you try to do something with strings, there’s a function that can do it better and faster.

The Route from $_GET to String

The global arrays in PHP contain request parameters. Either GET or POST. As you know if the page address is something like:


This means that you pass to the index.php file two parameters – “a” and “key” with their values: “b” and “value”. Now in this case you can dump the $_GET global array somewhere in index.php and you’ll receive something like this.

"a" => "b",
"key" => "value",

This is however pseudocode, but in fact $_GET will be very similar to this sample array.

$_GET to String

Very often when a developer need to process the $_GET array to a string, which means generating again the query string from $_GET, he often comes to some operation like this one.

$queryString = '';
foreach ($_GET as $key => $value) {
$queryString .= $key . '=' . $value . '&';

However this will result in something quite ugly like a=b&key=value& which comes with a trailing & at the end of the string.

There is however another approach – using an array.

$queryString = array();
foreach ($_GET as $key => $value) {
$queryString[] = $key . '=' . $value;
$queryString = implode('&', $queryString);

But that invokes one function more and this is still not the most elegant solution. As I said at the beginning PHP is full of useful functions and here comes the http_build_query.


This is exactly what you need. As it name describe you can build the query string even by using a different from & separator.

$queryString = http_build_query($_GET, '', '|');

Thus $queryString will contain a=b|key=value and at least the code will look pritier.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Stoimen Popov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}