PHP Build an URL-encoded query string from an array


Example

The http_build_query() will create a query string from an array or object. These strings can be appended to a URL to create a GET request, or used in a POST request with, for example, cURL.

$parameters = array(
    'parameter1' => 'foo',
    'parameter2' => 'bar',
);
$queryString = http_build_query($parameters);

$queryString will have the following value:

parameter1=foo&parameter2=bar

http_build_query() will also work with multi-dimensional arrays:

$parameters = array(
    "parameter3" => array(
        "sub1" => "foo",
        "sub2" => "bar",
    ),
    "parameter4" => "baz",
);
$queryString = http_build_query($parameters);

$queryString will have this value:

parameter3%5Bsub1%5D=foo&parameter3%5Bsub2%5D=bar&parameter4=baz

which is the URL-encoded version of

parameter3[sub1]=foo&parameter3[sub2]=bar&parameter4=baz