Definition and Usage
The http_build_query()
function encodes an array or object into a URL-compatible string to generate a query string.
This function is particularly useful when building HTTP requests or constructing URLs based on arrays or objects.
Basic Example
The following is a basic example of creating a URL query string from an array.
$data = array(
'name' => 'John Doe',
'age' => 30,
'city' => 'New York'
);
$queryString = http_build_query($data);
echo $queryString;
// Output: 'name=John+Doe&age=30&city=New+York'
Syntax
http_build_query(
array|object $data,
string $numeric_prefix = "",
?string $arg_separator = null,
int $encoding_type = PHP_QUERY_RFC1738
): string
Parameters
$data
An array or object that will be encoded into a URL-compatible query string.
- If
$data
is an array, it can be a simple one-dimensional array or a nested array (an array of arrays). - If
$data
is an object, only its public properties will be included in the result.
$numeric_prefix
If the base array uses numeric indices and this parameter is provided, the prefix will be added only to those numeric keys. The default value is an empty string (''
).
This helps ensure valid variable names when decoding data later in PHP or other CGI applications.
For example, given the following array:
$data = array(
1 => 'foo',
2 => 'bar',
3 => 'baz',
);
$queryString = http_build_query($data, 'my_');
echo $queryString;
// Output: 'my_1=foo&my_2=bar&my_3=baz'
Passing this array to http_build_query()
with the second argument set to 'my_'
prefixes the numeric keys with my_
. This creates valid variable names for PHP or other CGI applications. If the second argument is not set, the numeric keys remain unchanged.
$arg_separator
The argument separator used to separate key-value pairs. By default, it uses the value of PHP's arg_separator.output
configuration from the php.ini
file, which is an ampersand (&
).
If set to null
, no separator will be used (i.e., key-value pairs won’t be separated).
For example, given the following array:
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
);
Using http_build_query()
without specifying the third argument generates a query string separated by the default ampersand:
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
);
$queryString = http_build_query($data);
echo $queryString;
// Output: 'foo=bar&baz=boom&cow=milk'
Setting the third argument to an empty string (''
) results in no separators:
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
);
$queryString = http_build_query($data, '', '');
echo $queryString;
// Output: 'foo=barbaz=boomcow=milk'
Setting the third argument to a comma (','
) produces a comma-separated query string:
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
);
$queryString = http_build_query($data, '', ',');
echo $queryString;
// Output: 'foo=bar,baz=boom,cow=milk'
Setting the third argument to a semicolon (';'
) produces a semicolon-separated query string:
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
);
$queryString = http_build_query($data, '', ';');
echo $queryString;
// Output: 'foo=bar;baz=boom;cow=milk'
$encoding_type
Specifies the encoding type. The default value is PHP_QUERY_RFC1738
.
PHP_QUERY_RFC1738
is a PHP constant that encodes data according to RFC 1738 and theapplication/x-www-form-urlencoded
MIME type. It behaves like theurlencode()
function, encoding all characters except uppercase and lowercase letters, numbers, and-
,_
, and.
characters. Spaces are encoded as+
.PHP_QUERY_RFC3986
is a PHP constant that encodes data according to RFC 3986. It behaves like therawurlencode()
function, encoding all characters except uppercase and lowercase letters, numbers, and-
,.
,_
, and~
characters. Spaces are encoded as%20
.
For example, given the following array:
$data = array(
'name' => 'John Doe',
'age' => 30,
'city' => 'New York'
);
Passing this array to http_build_query()
with the default encoding type (PHP_QUERY_RFC1738
):
$data = array(
'name' => 'John Doe',
'age' => 30,
'city' => 'New York'
);
$queryString = http_build_query($data, '', null, PHP_QUERY_RFC1738);
echo $queryString;
// Output: 'name=John+Doe&age=30&city=New+York'
Note that spaces are encoded as +
.
Passing the same array with encoding type set to PHP_QUERY_RFC3986
:
$data = array(
'name' => 'John Doe',
'age' => 30,
'city' => 'New York'
);
$queryString = http_build_query($data, '', null, PHP_QUERY_RFC3986);
echo $queryString;
// Output: 'name=John%20Doe&age=30&city=New%20York'
Here, spaces are encoded as %20
.
Practical Examples
Here are some practical examples demonstrating how to use the http_build_query()
function in various scenarios.
Creating HTTP GET Requests
The http_build_query()
function is useful when you need to create HTTP GET requests to send data from a web application to a server. For example, you can include search terms or filtering criteria in a URL to send them to the server.
$params = array(
'search_query' => 'keyword',
'category' => 'books',
'sort' => 'relevance'
);
$query_string = http_build_query($params);
$url = 'https://example.com/search?' . $query_string;
// The resulting $url will be:
// "https://example.com/search?search_query=keyword&category=books&sort=relevance"
Creating API Requests
When sending requests to a remote API, you can generate URLs that include the API endpoint and request parameters.
$api_endpoint = 'https://api.example.com/data';
$api_key = 'your_api_key';
$params = array(
'api_key' => $api_key,
'action' => 'get_data',
'format' => 'json'
);
$api_url = $api_endpoint . '?' . http_build_query($params);
// The resulting $api_url will be:
// "https://api.example.com/data?api_key=your_api_key&action=get_data&format=json"
Generating Action URLs for HTML Forms
When creating web forms, you often need to set the URL in the form's action
attribute. The http_build_query()
function can help by encoding form data into the URL.
$form_data = array(
'username' => 'user123',
'password' => 'secret',
'remember' => 1
);
$action_url = 'https://example.com/login?' . http_build_query($form_data);
// Output: 'https://example.com/login?username=user123&password=secret&remember=1'
// This URL can be used as the <form> element's action attribute.
Generating Query Strings from Objects
The http_build_query()
function can also convert an object's public properties into a query string. Note that only public properties are included; protected and private properties are excluded.
class UserProfile {
public $id = 101;
public $username = 'happy_coder';
public $status = 'online';
protected $password = 'secret'; // protected/private 속성은 제외됨
}
$user_profile_object = new UserProfile();
$query_string_object = http_build_query($user_profile_object);
echo 'https://api.example.com/profile?' . $query_string_object;
// Output: 'https://api.example.com/profile?id=101&username=happy_coder&status=online'
References
See also
- PHP URL Encoding Functions
- PHP urlencode() Function – Encoding a URL Query Parameter Value
- PHP rawurlencode() Function – Safely Encoding URI Components
- PHP URL Decoding Functions
- PHP urldecode() Function – Decoding URLs Encoded with urlencode()
- PHP rawurldecode() Function – Decoding URLs Encoded with rawurlencode()
- PHP parse_str() Function – Parse URL Query Strings into Variables