Understanding and Using PHP's parse_str() Function
This article explains PHP's parse_str() function, its syntax, basic usage, handling of nested and duplicate query strings, optional parameters, security tips, and provides example code to help developers efficiently parse query strings in backend applications.
In PHP programming, the parse_str() function parses a query string into variables and values, optionally storing them in an array.
Basic Syntax of parse_str()
<code>void parse_str ( string $string [, array &$result ] )</code>The function accepts a string $string and, if a second argument $result is provided, fills that array with the parsed variables; otherwise it creates global variables.
How to Use parse_str()
Basic Usage
<code>$queryString = "name=John&age=25&country=USA";
parse_str($queryString, $result);
echo $result['name']; // Output: John
echo $result['age']; // Output: 25
echo $result['country']; // Output: USA</code>This example converts a query string into an associative array and accesses values via keys.
Handling Nested Query Strings
<code>$queryString = "person[name]=John&person[age]=25&person[country]=USA";
parse_str($queryString, $result);
echo $result['person']['name']; // Output: John
echo $result['person']['age']; // Output: 25
echo $result['person']['country']; // Output: USA</code>The function parses nested structures into multidimensional arrays.
Handling Duplicate Variable Names
<code>$queryString = "name=John&name=Smith&name=Doe";
parse_str($queryString, $result);
print_r($result);
</code>When the same variable appears multiple times, parse_str() stores the values in an array.
Beyond these basics, parse_str() offers optional parameters to change the separator and assignment characters, and it is useful for parsing URL query strings, form data, cookies, and more. Security considerations require validating and filtering user input to avoid vulnerabilities.
PHP Learning Recommendations
Vue3+Laravel8+Uniapp tutorial
Vue3+TP6+API social e‑commerce system tutorial
Swoole from beginner to advanced course
Workerman+TP6 instant‑messaging system promotion
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.