parse_str

parse_str(string $string, array &$result): void

Parses a URL query string into an array (the second argument is mandatory since PHP 8.0); dots and spaces in keys are converted to underscores.

C C23

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

/* Hand-written parsing: strtok splits on &, + becomes space (%XX decoding omitted to keep the demo lean) */
static void decode(char *s) {
    for (; *s; s++) {
        if (*s == '+') *s = ' ';
    }
}

int main(void) {
    char qs[] = "q=hello+world&lang=zh&page=2";
    char *pair = strtok(qs, "&");
    while (pair != NULL) {
        char *eq = strchr(pair, '=');
        if (eq != NULL) {
            *eq = '\0';
            decode(pair);
            decode(eq + 1);
            printf("%s=%s\n", pair, eq + 1);
        }
        pair = strtok(NULL, "&");
    }
    return 0;
}
Output
q=hello world
lang=zh
page=2

C++ C++26

C++26
#include <iostream>
#include <string>

// Hand-written parsing: split on & and =, + becomes space (%XX decoding omitted to keep the demo lean)
static std::string decode(std::string s) {
    for (char &ch : s) {
        if (ch == '+') ch = ' ';
    }
    return s;
}

int main() {
    std::string qs = "q=hello+world&lang=zh&page=2";
    size_t start = 0;
    while (start < qs.size()) {
        size_t amp = qs.find('&', start);
        if (amp == std::string::npos) amp = qs.size();
        std::string pair = qs.substr(start, amp - start);
        start = amp + 1;
        size_t eq = pair.find('=');
        if (eq == std::string::npos) {
            continue;
        }
        std::cout << decode(pair.substr(0, eq)) << "=" << decode(pair.substr(eq + 1)) << "\n";
    }
    return 0;
}
Output
q=hello world
lang=zh
page=2

C# v11.0.100

v11.0.100
// No ready-made parser in the standard library: hand-split on & / =; note UnescapeDataString does not handle +, replace it with a space first
static string Decode(string s) => Uri.UnescapeDataString(s.Replace("+", " "));

static void ParseQuery(string qs) {
    foreach (var pair in qs.Split('&')) {
        int eq = pair.IndexOf('=');
        string k = eq < 0 ? pair : pair[..eq];
        string v = eq < 0 ? "" : pair[(eq + 1)..];
        Console.WriteLine(Decode(k) + "=" + Decode(v));
    }
}

ParseQuery("q=hello+world&lang=zh&page=2");
Output
q=hello world
lang=zh
page=2

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net/url"
)

func main() {
	// url.ParseQuery: returns url.Values (map[string][]string), + decodes to space; invalid escapes return an error
	v, err := url.ParseQuery("q=hello+world&lang=zh&page=2")
	if err != nil {
		panic(err)
	}
	fmt.Println(v["q"], v["lang"], v["page"])
	// A missing key returns an empty slice
	fmt.Println(v["missing"])
}
Output
[hello world] [zh] [2]
[]

Java v27.0.1

v27.0.1
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

public class Main {
    // No query-string parser in the standard library: hand-split on & + URLDecoder (decodes both + and %XX)
    static void parseQuery(String qs) {
        for (String pair : qs.split("&")) {
            int eq = pair.indexOf('=');
            String k = eq < 0 ? pair : pair.substring(0, eq);
            String v = eq < 0 ? "" : pair.substring(eq + 1);
            System.out.println(URLDecoder.decode(k, StandardCharsets.UTF_8)
                    + "=" + URLDecoder.decode(v, StandardCharsets.UTF_8));
        }
    }

    public static void main(String[] args) {
        parseQuery("q=hello+world&lang=zh&page=2");
    }
}
Output
q=hello world
lang=zh
page=2

JavaScript v26.13.1

v26.13.1
// URLSearchParams: the modern standard query-string interface; both + and %20 decode to space
const sp = new URLSearchParams("q=hello+world&lang=zh&page=2");
console.log(sp.get("q"));
console.log(sp.get("lang"), sp.get("page"));
// A missing key returns null; there is no "auto-create variables" mechanism whatsoever
console.log(sp.get("missing"));
Output
hello world
zh 2
null

PHP v8.6.0

v8.6.0
// parse_str: parses the query string into an array (recommended: always pass the 2nd argument explicitly to receive the result)
parse_str("q=hello+world&lang=zh&page=2", $result);
print_r($result);
// Bare calls (single argument, auto-creating variables) deprecated in 7.2, removed in 8.0: the end of the historic variable-pollution problem
try {
    parse_str("user=admin&action=login");
} catch (ArgumentCountError) {
    echo "ArgumentCountError caught\n";
}
// Dots and spaces in key names still rewrite to underscores: a.b and "a b" both land in a_b (the latter overwriting the former)
parse_str("a.b=1&a b=2", $m);
echo $m["a_b"], "\n";
Output
Array
(
    [q] => hello world
    [lang] => zh
    [page] => 2
)
ArgumentCountError caught
2

Python v3.15.2

v3.15.2
from urllib.parse import parse_qs, parse_qsl

# parse_qs: values are lists (same-name keys aggregate automatically); + decodes to space; empty-valued keys dropped by default
print(parse_qs("q=hello+world&lang=zh&page=2"))
# parse_qsl: a list of key-value tuples, occurrence order preserved
print(parse_qsl("q=hello+world&lang=zh&page=2"))
# Python never "auto-creates variables": parse results are always explicit return values, no variable-injection risk
Output
{'q': ['hello world'], 'lang': ['zh'], 'page': ['2']}
[('q', 'hello world'), ('lang', 'zh'), ('page', '2')]

Rust v1.99.1

v1.99.1
// No query-string parsing in the standard library: hand-split on & / = + percent-decoding (+ treated as space)
fn decode(s: &str) -> String {
    let plus_fixed = s.replace('+', " ");
    let bytes = plus_fixed.as_bytes();
    let mut out = String::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let Ok(b) = u8::from_str_radix(&plus_fixed[i + 1..i + 3], 16) {
                out.push(b as char);
                i += 3;
                continue;
            }
        }
        let ch = plus_fixed[i..].chars().next().unwrap();
        out.push(ch);
        i += ch.len_utf8();
    }
    out
}

fn main() {
    for pair in "q=hello+world&lang=zh&page=2".split('&') {
        let (k, v) = match pair.split_once('=') {
            Some((k, v)) => (k, v),
            None => (pair, ""),
        };
        println!("{}={}", decode(k), decode(v));
    }
}
Output
q=hello world
lang=zh
page=2

TypeScript v26.13.1

v26.13.1
// URLSearchParams: the modern standard query-string interface; both + and %20 decode to space
const sp = new URLSearchParams("q=hello+world&lang=zh&page=2");
console.log(sp.get("q"));
console.log(sp.get("lang"), sp.get("page"));
// A missing key returns null; there is no "auto-create variables" mechanism whatsoever
console.log(sp.get("missing"));
Output
hello world
zh 2
null

Language differences

C: nothing built-in — strtok-based hand parsing (shown); note strtok mutates the input and is not thread-safe; %XX decoding needs extra code.

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

C#: hand-written splitting; Uri.UnescapeDataString does not handle + (replace it with a space first), while the legacy HttpUtility.ParseQueryString (System.Web) does.

Go: url.ParseQuery returns url.Values (map[string][]string) plus an error — invalid percent escapes are rejected, stricter than PHP's lenient parsing; Get returns the first value.

Java: no query-string parser in the standard library (Spring offers @RequestParam, Servlet offers request.getParameter); when hand-rolling, URLDecoder.decode handles both + and %XX.

JavaScript: URLSearchParams is the modern standard; get returns the first value, getAll all of them; no automatic-variable mechanism whatsoever.

PHP: a historic security hot spot — the bare call parse_str($s) used to create variables in the current scope directly (the root of external variable-injection holes in the register_globals era; deprecated with E_DEPRECATED in 7.2, the second argument became mandatory in 8.0 where the bare call throws ArgumentCountError); always pass the second array argument. Dots, spaces (and unpaired square brackets) in keys are rewritten to underscores (legacy, rooted in variable-name validity rules); duplicate keys overwrite by default — tags[]=a&tags[]=b is required to aggregate into an array (every other CGI-standard language aggregates automatically); subject to max_input_vars; on the input side prefer filter_input(INPUT_GET, ...).

Python: parse_qs values are always lists (duplicate keys aggregate) and empty-value keys are dropped by default (pass keep_blank_values=True); parse_qsl keeps ordered pairs; no variable-injection concept.

Rust: nothing in std — the example hand-writes decoding; the url crate (form_urlencoded::parse) for real work.

TypeScript: same as JavaScript.