Over a million developers have joined DZone.

PHP: Fetch $_GET as String with http_build_query()

DZone's Guide to

PHP: Fetch $_GET as String with http_build_query()

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

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.

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}