PHP: Fetch $_GET as String with http_build_query()

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:

http://www.example.com/index.php?a=b&key=value

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.

array(
	"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.

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.

3 thoughts on “PHP: Fetch $_GET as String with http_build_query()

  1. @Gero – getenv(‘QUERY_STRING’) or $_SERVER[‘QUERY_STRING’] whatever is OK, but what if you have an array and you want to build the query string. Imagine you’ve an empty $_GET but you want to generate a query string from this: array(‘a’ => ‘b’, ‘c’ => ‘d’)?

  2. It does make sense this way around. Still, using $_GET as an example seems bad to me, since it was generated exactly from the data you want to end up with.

Leave a Reply

Your email address will not be published. Required fields are marked *