PHP Reference ยท String Functions
PHP http_build_query() function
Reference for PHP http_build_query(): turn an array into a URL-encoded query string, nested arrays, booleans and null, separators and encoding types.
http_build_query() converts an array (or an object's public properties) into a URL-encoded query string such as page=2&sort=name. It encodes keys and values for you, so it is the safest way to assemble the part of a URL after the ?.
Nested arrays become bracket notation (filter[color]=red), which PHP reads back into the same nested array when it parses the query. This makes the function the natural counterpart of parse_str().
<?php echo http_build_query(["page" => 2, "q" => "a b"]); // page=2&q=a+b
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
http_build_query( array|object $data, string $numeric_prefix = "", ?string $arg_separator = null, int $encoding_type = PHP_QUERY_RFC1738 ): string
| Name | Description |
|---|---|
$data |
An array or object. For objects, only public properties are used. Nested arrays and objects are expanded with bracket notation. |
$numeric_prefix |
Text added in front of numeric keys of the top-level array, so the result is a valid variable name. |
$arg_separator |
The character between pairs. null uses the arg_separator.output ini setting, which is & by default. |
$encoding_type |
PHP_QUERY_RFC1738 (default) writes spaces as +; PHP_QUERY_RFC3986 writes them as %20. |
Return value: the encoded string, possibly empty. It has no leading ?.
Usage notes
- No leading
?. Add it yourself:$url . "?" . http_build_query($params). nullvalues are skipped;falseandtruebecome0and1; an empty string stays askey=.- Nested structures use encoded brackets (
filter%5Bcolor%5D=red), and lists get explicit indexes (tags%5B0%5D=a), not empty brackets. Servers running PHP decode them back into arrays, other stacks may not. - Use
&only inside HTML attributes. For a real request or a redirect, keep the default&; for a link inside HTML, escape the whole URL withhtmlspecialchars(). - Pick the encoding that fits the receiver. Form-style
+is fine for most query strings; usePHP_QUERY_RFC3986when the value will be placed in a path or compared byte for byte. - Resources and closures cannot be encoded and are ignored.
- Order is kept. Pairs appear in the array's order, which matters for signed URLs.
Related
urlencode(),parse_str(),parse_url(),json_encode()- Lessons: Forms, REST APIs