Home >Backend Development >PHP Tutorial >How Can I Parse a Query String into an Array in PHP?
Parsing Query Strings into Arrays
In the realm of web programming, it's often necessary to manipulate query strings – snippets of data appended to URLs. One common task is to parse these strings into structured arrays for easier handling.
Consider this query string:
pg_id=2&parent_id=2&document&video
Our goal is to convert this string into an array resembling:
array( 'pg_id' => 2, 'parent_id' => 2, 'document' => , 'video' => )
The Solution: parse_str Function
PHP's parse_str function excels at this task. It takes two parameters: the query string to parse and an output array variable. By specifying the second parameter, we instruct the function to populate an array with retrieved key-value pairs.
Code Demonstration
$queryString = "pg_id=2&parent_id=2&document&video"; parse_str($queryString, $queryArray); print_r($queryArray);
This code assigns the query string to the $queryString variable and invokes parse_str to populate the empty $queryArray with the parsed data. The resulting array can be displayed using print_r.
Output:
Array ( [pg_id] => 2 [parent_id] => 2 [document] => [video] => )
Additional Notes
The above is the detailed content of How Can I Parse a Query String into an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!