Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Get deep insight into Node.js applications with real-time metrics, CPU profiling, and heap snapshots with N|Solid from NodeSource. Learn more.

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.

Node.js application metrics sent directly to any statsd-compliant system. Get N|Solid

Topics:

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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}