PHP Reference ยท String Functions
PHP parse_str() function
Reference for PHP parse_str(): turn a URL query string into an array, nested bracket keys, decoding rules and why the result argument is required.
parse_str() parses a query string such as a=1&b=2 into an array. It decodes percent-escapes and plus signs, and it understands bracket notation, so tags[]=x&tags[]=y becomes a nested array exactly like the one PHP builds for $_GET.
The function does not return the array. It fills a variable that you pass by reference as the second argument. Before PHP 8.0 the argument was optional and PHP created variables in the current scope; that behavior was dangerous and has been removed, so the result argument is now required.
<?php parse_str("name=Ada&langs[]=php&langs[]=sql", $data); print_r($data);
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
parse_str(string $string, array &$result): void
| Name | Description |
|---|---|
$string |
The query string, without the leading ?. |
$result |
Receives the array of parsed values. Passed by reference and always overwritten. |
Return value: nothing (void).
Usage notes
- The result is a reference argument. Calling
parse_str($s)with one argument is an error in PHP 8. - Every value is a string (or an array of strings). Convert numbers and booleans yourself, or use
filter_var(). - Names are rewritten. Dots and spaces in a key become underscores, and a leading space is dropped, to match legacy
$_GETnaming. - A key with no
=(flag) gets an empty string; repeated plain keys keep the last value unless you use[]. - Limits apply. PHP stops after
max_input_varspairs (1000 by default) and limits nesting depth, so huge queries are truncated. - Already decoded for requests. In a web request
$_GETholds the parsed query; useparse_str()for query strings from elsewhere, such as the output ofparse_url(). - Opposite direction:
http_build_query().
Related
http_build_query(),parse_url(),urldecode(),$_GET- Lessons: Forms, Superglobals