http_build_query

http_build_query(array|object $data, string $numeric_prefix = "", ?string $arg_separator = null, int $enc_type = PHP_QUERY_RFC1738): string

Serializes an array (nested ones included) into a URL-encoded query string, the inverse of parse_str; spaces are encoded as + by default.

C C23

C23
#include <stdio.h>
#include <string.h>

/* Hand-written percent-encoding: RFC 3986 unreserved characters pass through, everything else encodes as %XX (space becomes %20) */
static void print_encoded(const char *s) {
    for (; *s; s++) {
        if ((*s >= 'A' && *s <= 'Z') || (*s >= 'a' && *s <= 'z') ||
            (*s >= '0' && *s <= '9') || strchr("-_.~", *s) != NULL) {
            putchar(*s);
        } else {
            printf("%%%02X", (unsigned char)*s);
        }
    }
}

int main(void) {
    const char *data[][2] = {{"q", "hello world"}, {"t", "a b&c=d"}};
    for (int i = 0; i < 2; i++) {
        if (i > 0) putchar('&');
        print_encoded(data[i][0]);
        putchar('=');
        print_encoded(data[i][1]);
    }
    putchar('\n');
    return 0;
}
Output
q=hello%20world&t=a%20b%26c%3Dd

C++ C++26

C++26
#include <cctype>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>

// Hand-written percent-encoding: RFC 3986 unreserved characters pass through, everything else encodes as %XX (space becomes %20)
static std::string encode_component(const std::string &s) {
    std::string out;
    char buf[8];
    for (unsigned char ch : s) {
        if (std::isalnum(ch) || std::strchr("-_.~", static_cast<char>(ch)) != nullptr) {
            out += static_cast<char>(ch);
        } else {
            std::snprintf(buf, sizeof buf, "%%%02X", ch);
            out += buf;
        }
    }
    return out;
}

int main() {
    std::vector<std::pair<std::string, std::string>> data = {
        {"q", "hello world"}, {"t", "a b&c=d"}};
    std::string qs;
    for (size_t i = 0; i < data.size(); i++) {
        if (i > 0) qs += '&';
        qs += encode_component(data[i].first) + "=" + encode_component(data[i].second);
    }
    std::cout << qs << "\n";
    return 0;
}
Output
q=hello%20world&t=a%20b%26c%3Dd

C# v11.0.100

v11.0.100
// Uri.EscapeDataString: RFC 3986 style, space encodes as %20 (not +)
static string BuildQuery(IEnumerable<KeyValuePair<string, string>> data) {
    return string.Join("&", data.Select(kv =>
        Uri.EscapeDataString(kv.Key) + "=" + Uri.EscapeDataString(kv.Value)));
}

var data = new[] {
    new KeyValuePair<string, string>("q", "hello world"),
    new KeyValuePair<string, string>("t", "a b&c=d"),
};
Console.WriteLine(BuildQuery(data));
Output
q=hello%20world&t=a%20b%26c%3Dd

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net/url"
)

func main() {
	// url.Values.Encode: map[string][]string → query string; keys sorted alphabetically (deterministic output)
	v := url.Values{}
	v.Add("q", "hello world")
	v.Add("lang", "zh")
	v.Add("tags", "php")
	v.Add("tags", "web")
	fmt.Println(v.Encode())
	fmt.Println(url.Values{"t": []string{"a b&c=d"}}.Encode())
}
Output
lang=zh&q=hello+world&tags=php&tags=web
t=a+b%26c%3Dd

Java v27.0.1

v27.0.1
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // URLEncoder: space encodes as + (form style); the standard library has no "array expansion" — nested structures need your own convention
        Map<String, String> data = new LinkedHashMap<>();
        data.put("q", "hello world");
        data.put("lang", "zh");
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> e : data.entrySet()) {
            if (sb.length() > 0) sb.append('&');
            sb.append(URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8))
              .append('=')
              .append(URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8));
        }
        System.out.println(sb);
        System.out.println("t=" + URLEncoder.encode("a b&c=d", StandardCharsets.UTF_8));
    }
}
Output
q=hello+world&lang=zh
t=a+b%26c%3Dd

JavaScript v26.13.1

v26.13.1
// URLSearchParams construction: object → query string (insertion order preserved); space encodes as +
const params = new URLSearchParams({ q: "hello world", lang: "zh" });
params.append("tags", "php");
params.append("tags", "web"); // Repeated keys with the same name (no PHP-style tags[0]/tags[1] indexing)
console.log(params.toString());
console.log(new URLSearchParams({ t: "a b&c=d" }).toString());
Output
q=hello+world&lang=zh&tags=php&tags=web
t=a+b%26c%3Dd

PHP v8.6.0

v8.6.0
// http_build_query: array → URL-encoded query string (the inverse of parse_str); space encodes as + (RFC 1738 style)
$data = ["q" => "hello world", "lang" => "zh", "tags" => ["php", "web"]];
echo http_build_query($data), "\n";
// Numeric-indexed arrays auto-expand into tags[0]=... (brackets encoded as %5B/%5D)
echo http_build_query(["t" => "a b&c=d"]), "\n";
Output
q=hello+world&lang=zh&tags%5B0%5D=php&tags%5B1%5D=web
t=a+b%26c%3Dd

Python v3.15.2

v3.15.2
from urllib.parse import quote, urlencode

# urlencode: dict → query string; quote_via defaults to quote_plus (space as +, matching PHP)
data = {"q": "hello world", "lang": "zh", "tags": ["php", "web"]}
print(urlencode(data, doseq=True))  # doseq: lists expand into repeated same-name keys (no PHP-style [0]/[1] indexing)
print(urlencode({"t": "a b&c=d"}))
# RFC 3986 style with space as %20: quote_via=quote
print(urlencode({"t": "a b&c=d"}, quote_via=quote))
Output
q=hello+world&lang=zh&tags=php&tags=web
t=a+b%26c%3Dd
t=a%20b%26c%3Dd

Rust v1.99.1

v1.99.1
// No query-string serialization in the standard library: hand-written percent-encoding (RFC 3986, space as %20)
fn encode_component(s: &str) -> String {
    let mut out = String::new();
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{:02X}", b)),
        }
    }
    out
}

fn main() {
    let data = [("q", "hello world"), ("t", "a b&c=d")];
    let qs: Vec<String> = data
        .iter()
        .map(|(k, v)| format!("{}={}", encode_component(k), encode_component(v)))
        .collect();
    println!("{}", qs.join("&"));
}
Output
q=hello%20world&t=a%20b%26c%3Dd

TypeScript v26.13.1

v26.13.1
// URLSearchParams construction: object → query string (insertion order preserved); space encodes as +
const params = new URLSearchParams({ q: "hello world", lang: "zh" });
params.append("tags", "php");
params.append("tags", "web"); // Repeated keys with the same name (no PHP-style tags[0]/tags[1] indexing)
console.log(params.toString());
console.log(new URLSearchParams({ t: "a b&c=d" }).toString());
Output
q=hello+world&lang=zh&tags=php&tags=web
t=a+b%26c%3Dd

Language differences

C: nothing built-in — hand-written RFC 3986 encoding (shown); nested structures and value typing need your own serialization convention.

C++: same hand-rolled approach as C; Boost.URL for real work.

C#: Uri.EscapeDataString is RFC 3986 (space as %20); the legacy HttpUtility.UrlEncode (System.Web) is the form style with space as + — precisely the two camps of the historical + vs %20 split.

Go: url.Values.Encode sorts keys alphabetically (unlike the insertion order of PHP/JS, but deterministic by nature); url.Values is map[string][]string under the hood, so repeated keys are arrays.

Java: URLEncoder.encode encodes space as + (form style); no nested-array expansion — multilevel structures need your own convention (commonly repeated tags=php&tags=web keys or JSON).

JavaScript: new URLSearchParams(object) keeps insertion order; arrays are expressed as repeated same-name keys (no [0]/[1] subscripts); space encodes to +.

PHP: defaults to PHP_QUERY_RFC1738 (space as +), pass PHP_QUERY_RFC3986 for %20; nested arrays expand automatically to tags[0]=php (brackets encoded as %5B/%5D — Go/JS/Python ecosystems generally do not understand such subscripts, so prefer repeated keys or JSON across languages); the third argument arg_separator overrides the separator (the arg_separator.output ini may also pollute output).

Python: urlencode(doseq=True) expands lists into repeated same-name keys; quote_via switches between the + and %20 styles; dicts keep insertion order.

Rust: nothing in std — the example hand-writes RFC 3986; the url crate (Url::query_pairs_mut) for real work.

TypeScript: same as JavaScript.