Skip to content

http_build_query() in PHP5

2010 February 8
by Richard Knop

I can’t tell how many times I need to pass some data via GET method to another PHP script and I always forget about this neat little function so I just do it like this (like a fool):

  1. $arr = array('foo' => 'bar',
  2.              'baz' => 'boom',
  3.              'cow' => 'milk');
  4. $query = array();
  5. foreach ($arr as $k => $v) {
  6.     $query[] = $k . '=' . $v;
  7. }
  8. $query = implode('&', $query);
  9. // foo=bar&baz=boom&cow=milk

When it’s so easy with the http_build_query() function:

  1. $query = http_build_query($arr);
  2. // foo=bar&baz=boom&cow=milk

This is also useful when using cURL to perform POST or GET calls.

2 Responses leave one →
  1. February 16, 2010

    Should it be join() instead of explode()?
    It would also be cool to add urlencode() to that function I think.

  2. February 19, 2010

    It should have been implode(), not explode(). My bad.

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS